{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "cedf868076a2"
   },
   "source": [
    "##### Copyright 2020 The Cirq Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "cellView": "form",
    "id": "906e07f6e562"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "19599098c1f9"
   },
   "source": [
    "# Introduction to Cirq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8bd3406cf99e"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.example.org/cirq/tutorials/educators/intro\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/educators/intro.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8m9ye4AS6dE4"
   },
   "source": [
    "[Cirq](https://github.com/quantumlib/cirq) is a framework for writing quantum algorithms for noisy intermediate scale quantum (NISQ) devices. Roughly speaking, NISQ devices are those with O(100) qubits that can enact O(1000) gates.  Because the resources for NISQ devices are so constrained, we believe that a framework for writing programs on these devices needs to be aware of all of the architectural properties of the device on which the algorithm is written. This is in contrast to other frameworks where there is a clean separation between the abstract model being used and the details of the device.  \n",
    "\n",
    "In this tutorial we will walk through the basics of writing quantum alogorithms in Cirq. Our final goal will be to write a variational ansatz for use in an optimization algorithm."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "cc948e49cecb"
   },
   "source": [
    "## Installing Cirq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rPgPbry6-mF3"
   },
   "source": [
    "To use Cirq one first needs to install Cirq.  Installation instructions are available at [cirq.readthedocs.io under \"Installing Cirq\"](https://cirq.readthedocs.io/en/stable/docs/install.html).  For the purpose of this tutorial, we run `pip install cirq` as shown in the following code cell to install the latest release of Cirq. \n",
    "\n",
    "> Different notebook execution systems exist, but for most part they have \"run\" button on a cell which you can click, or \"shift + enter\" is often the shortcut to run the cell. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "RlJBDvNgC00H"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install cirq --quiet\n",
    "    print(\"installed cirq.\")\n",
    "    import cirq\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GPjUqrK8DJTq"
   },
   "source": [
    "Let's check that Cirq has been successfully installed by importing Cirq and printing out a diagram of Google's Bristlecone device shown below.\n",
    "\n",
    "![Google's Bristecone chip](https://4.bp.blogspot.com/-b9akad6ismU/WpmyaJo-cYI/AAAAAAAACa8/mCqPBJxv5oUivy6Jq42FSOQYkeRlTmkiwCLcBGAs/s1600/image1.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "FTrmLyq4C2gf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                             (0, 5)────(0, 6)\n",
      "                                             │         │\n",
      "                                             │         │\n",
      "                                    (1, 4)───(1, 5)────(1, 6)────(1, 7)\n",
      "                                    │        │         │         │\n",
      "                                    │        │         │         │\n",
      "                           (2, 3)───(2, 4)───(2, 5)────(2, 6)────(2, 7)───(2, 8)\n",
      "                           │        │        │         │         │        │\n",
      "                           │        │        │         │         │        │\n",
      "                  (3, 2)───(3, 3)───(3, 4)───(3, 5)────(3, 6)────(3, 7)───(3, 8)───(3, 9)\n",
      "                  │        │        │        │         │         │        │        │\n",
      "                  │        │        │        │         │         │        │        │\n",
      "         (4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)────(4, 6)────(4, 7)───(4, 8)───(4, 9)───(4, 10)\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "(5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)───(5, 5)────(5, 6)────(5, 7)───(5, 8)───(5, 9)───(5, 10)───(5, 11)\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "         (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)────(6, 6)────(6, 7)───(6, 8)───(6, 9)───(6, 10)\n",
      "                  │        │        │        │         │         │        │        │\n",
      "                  │        │        │        │         │         │        │        │\n",
      "                  (7, 2)───(7, 3)───(7, 4)───(7, 5)────(7, 6)────(7, 7)───(7, 8)───(7, 9)\n",
      "                           │        │        │         │         │        │\n",
      "                           │        │        │         │         │        │\n",
      "                           (8, 3)───(8, 4)───(8, 5)────(8, 6)────(8, 7)───(8, 8)\n",
      "                                    │        │         │         │\n",
      "                                    │        │         │         │\n",
      "                                    (9, 4)───(9, 5)────(9, 6)────(9, 7)\n",
      "                                             │         │\n",
      "                                             │         │\n",
      "                                             (10, 5)───(10, 6)\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Test successful installation by printing out the Bristlecone device.\"\"\"\n",
    "print(cirq.google.Bristlecone)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "09zRgohCMiBs"
   },
   "source": [
    "This cell should run successfully, and the output should in fact be the grid of qubits for the Bristlecone device. If so, the install worked!\n",
    "\n",
    "> Be aware that Cirq is still alpha software, meaning **breaking changes can happen at any time**. If you don't want your project to suddenly go from working to not working when we a new version is released, you should depend on a *specific version* of Cirq and periodically bump that version to the latest one. For example, you can run `pip install cirq==x.y.z` to install version `x.y.z` of Cirq."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3340594dd8c1"
   },
   "source": [
    "## Qubits, Moments, Operations, and Circuits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8A7a3jcql1l5"
   },
   "source": [
    "In Cirq, circuits are represented either by a `Circuit` object. Conceptually:\n",
    "\n",
    "- Q `Circuit` is a collection of `Moment`s. \n",
    "- A `Moment` is a collection of `Operation`s that all act during the same abstract time slice. \n",
    "- An `Operation` is a an effect that operates on a specific subset of Qubits. \n",
    "  - The most common type of `Operation` is a `Gate` applied to several qubits (a \"`GateOperation`\"). \n",
    "  \n",
    "These ideas are illustrated by the following diagram."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "03b7d753ecd5"
   },
   "source": [
    "![Circuits, Moments, and Operations.](https://cirq.readthedocs.io/en/latest/_images/CircuitMomentOperation.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9768d38c9151"
   },
   "source": [
    "### Create a `Circuit`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "VFwmWPf7D057"
   },
   "source": [
    "A typical way to create a `Circuit` is shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "pE88WsFeDGfs"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "\n",
      "a: ───H───────────\n",
      "\n",
      "b: ───H───@───H───\n",
      "          │\n",
      "c: ───────X───────\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Creating a circuit.\"\"\"\n",
    "# Define three qubits.\n",
    "a = cirq.NamedQubit(\"a\")\n",
    "b = cirq.NamedQubit(\"b\")\n",
    "c = cirq.NamedQubit(\"c\")\n",
    "\n",
    "# Define a list of operations.\n",
    "ops = [cirq.H(a), cirq.H(b), cirq.CNOT(b, c), cirq.H(b)]\n",
    "\n",
    "# Create a circuit from the list of operations.\n",
    "circuit = cirq.Circuit(ops)\n",
    "print(\"Circuit:\\n\")\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-06jQwEdI4DJ"
   },
   "source": [
    "We can unpack this a bit and see all of the components for the circuit.\n",
    "\n",
    "The first thing we do is pick some qubits to use. There are many different types of qubits in Cirq, and you can define your own by inheriting from the `cirq.Qid` class. There's nothing inherently special or magical about these quantum id types such as `cirq.NamedQubit`. They simply identify what you wish to operate on, which is relevant when you are targeting a specific device. For example, if we were creating a circuit for the Bristlecone device and wanted to refer to the qubit in the left-most position, we would use `cirq.GridQubit(5, 0)`. (See the first diagram of the Bristlecone device we printed out.) For simplicity, in the previous cell we defined `cirq.NamedQubit`s which are simply qubits that can be identified by a name.\n",
    "\n",
    "Next, we encounter the object `cirq.H` which is a Hadamard gate with unitary\n",
    "\n",
    "$$\n",
    "H = {1 \\over \\sqrt{2}} \\left[ \\begin{array}[cc]  & 1 & 1  \\\\ 1 & -1 \\end{array}\\right] .\n",
    "$$\n",
    "\n",
    "In Cirq, `cirq.H` is an instance of the `cirq.HGate` class, which itself is a subclass of `Gate` (along with other classes). We can use Cirq to see the unitary matrix of `Gate` objects as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "YKfg575v1DQB"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.70710678+0.j,  0.70710678+0.j],\n",
       "       [ 0.70710678+0.j, -0.70710678+0.j]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"Get the unitary of a gate, here the Hadamard gate.\"\"\"\n",
    "cirq.unitary(cirq.H)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hJMAciW21KEg"
   },
   "source": [
    "We see that this agrees with the unitary for the Hadamard gate above.\n",
    "\n",
    "`Gate` objects have the ability to applied \"on\" one or more qubits.  There are two ways to do this for gates, either using the `on` method or by directly calling the gate on the qubits as if the gate were a function and the qubits were arguments.  For example to apply the `H` onto qubit `a` we can say `cirq.H.on(a)` or `cirq.H(a)`.\n",
    "\n",
    "The result of those expressions is a `GateOperation` object, which is a type of `Operation`.\n",
    "\n",
    "> **Note**: In Cirq, there is a strong distinction between `Operation`s and `Gate`s. An `Operation` is associated with specific qubits and can be put in `Circuit`s. A `Gate` has unspecified qubits, and will produce an operation when acting on qubits.\n",
    "\n",
    "Once you have a collection of operations, you can construct a `Circuit` by passing the operations into the constructor for a `Circuit`:\n",
    "\n",
    "```\n",
    "ops = [list of operations]\n",
    "circuit = cirq.Circuit(ops)\n",
    "```\n",
    "\n",
    "The last thing we did in the example code was use the (surprisingly useful) ability to print the circuit as a text diagram.\n",
    "\n",
    "The diagram is visually helpful, but it doesn't really get into the internal details of how the `Circuit` is represented. As mentioned, a `Circuit` is made up of a sequence of `Moment` objects, and each `Moment` object is a list of non-overlapping `Operation`s. To see this internal structure, we can iterate over the `Moment`s in the `Circuit` and print them out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "hH-y4JiEMv25"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "\n",
      "a: ───H───────────\n",
      "\n",
      "b: ───H───@───H───\n",
      "          │\n",
      "c: ───────X───────\n",
      "\n",
      "Moments in the circuit:\n",
      "\n",
      "Moment 0: H(a) and H(b)\n",
      "Moment 1: CNOT(b, c)\n",
      "Moment 2: H(b)\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Print out the moments in a circuit.\"\"\"\n",
    "print(\"Circuit:\\n\")\n",
    "print(circuit)\n",
    "\n",
    "print(\"\\nMoments in the circuit:\\n\")\n",
    "for i, moment in enumerate(circuit):\n",
    "    print('Moment {}: {}'.format(i, moment))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pm5iC7MNQY6-"
   },
   "source": [
    "We see that this circuit consists of three moments. For even more on the underlying structure of a circuit, we can print the circuit's `repr`. This returns a more detailed (and usually less readable) expression."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "2Y6zG_peQG1y"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cirq.Circuit([\n",
      "    cirq.Moment(\n",
      "        cirq.H(cirq.NamedQubit('a')),\n",
      "        cirq.H(cirq.NamedQubit('b')),\n",
      "    ),\n",
      "    cirq.Moment(\n",
      "        cirq.CNOT(cirq.NamedQubit('b'), cirq.NamedQubit('c')),\n",
      "    ),\n",
      "    cirq.Moment(\n",
      "        cirq.H(cirq.NamedQubit('b')),\n",
      "    ),\n",
      "])\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Print the repr of a circuit.\"\"\"\n",
    "print(repr(circuit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "zyVbU8yfW_qi"
   },
   "source": [
    "Although it is less readable, the usefulness of printing the `repr` is that it includes *all* the gory details which can be useful when debugging. The `repr` is also a valid python expression that evaluates to the circuit.\n",
    "For example, if we notice that a circuit generated in some complicated way triggers a bug in a simulator, copy-pasting the generated circuit's `repr` into a test, and then working from there, is a simple way to decouple the reproduction of the bug from the circuit generation code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0bb8611c3865"
   },
   "source": [
    "### More ways to create `Circuit`s"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uaDb6B_jPgrb"
   },
   "source": [
    "Above we created a `Circuit` by passing in a list of operations to its constructor.  In Cirq, there are many ways to construct and modify circuits, and each of these is useful in different contexts.  Here are a few examples:\n",
    "\n",
    "\n",
    "1. `Circuit(...)`: This is the simplest way to make a circuit. Give this method some operations, and out pops a circuit.\n",
    "2.  `append`:  `Circuit`s are mutable. You can start with an empty `circ = cirq.Circuit()` and simply `circ.append(operations)` to add on more and more operations .\n",
    "3. `insert`:  Instead of appending, you can insert before a particular moment location (labeled by an integer index).\n",
    "\n",
    "One interesting, and extremely convenient, fact about `Circuit(...)`, `append`, and `insert` is that they \"auto flatten\" whatever you give them.\n",
    "You *can* give them a list of operations, but you can also give them\n",
    "\n",
    "- a list *of lists* of operations,\n",
    "- a generator function that sometimes yields tuples of operations and other times yields individual operations,\n",
    "- or just a single operation (without a list around it).\n",
    "\n",
    "If it can recursively iterated into individual operations, these three methods will take it.\n",
    "\n",
    "> The above idea uses a concept we call an `OP_TREE` in Cirq. An `OP_TREE` is not a class, but a contract. The basic idea is that if the input can be iteratively flattened into a list of operations, then the input is an `OP_TREE`.\n",
    "\n",
    "The main place where auto-flattening is useful is when you are building a circuit's operations using generators. \n",
    "\n",
    "> Recall that, in Python, functions that have a `yield` statement are *generators*. Generators are functions that act as *iterators*. \n",
    "\n",
    "In this context, auto-flattening means that generators producing operations for a circuit can simply `yield` sub-generators (instead of iterating over them and yielding their items). We show an example of this below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "QFoV-eOE1tGN"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0: ───@───X───@───────────────────────────────────────\n",
      "      │   │   │\n",
      "1: ───X───@───X───@───X───@───────────────────────────\n",
      "                  │   │   │\n",
      "2: ───────────────X───@───X───@───X───@───────────────\n",
      "                              │   │   │\n",
      "3: ───────────────────────────X───@───X───@───X───@───\n",
      "                                          │   │   │\n",
      "4: ───────────────────────────────────────X───@───X───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Creating a circuit from generator functions.\"\"\"\n",
    "def xor_swap(a, b):\n",
    "    \"\"\"Swaps two qubits with three CNOTs.\"\"\"\n",
    "    yield cirq.CNOT(a, b)\n",
    "    yield cirq.CNOT(b, a)\n",
    "    yield cirq.CNOT(a, b)\n",
    "\n",
    "\n",
    "def left_rotate(qubits):\n",
    "    \"\"\"Rotates qubits to the left.\"\"\"\n",
    "    for i in range(len(qubits) - 1):\n",
    "        a, b = qubits[i: i + 2]\n",
    "        yield xor_swap(a, b)\n",
    "\n",
    "\n",
    "# Get five qubits on a line.\n",
    "line = cirq.LineQubit.range(5)\n",
    "\n",
    "# Create a circuit which rotates the qubits to the left.\n",
    "print(cirq.Circuit(left_rotate(line)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ae159315c56d"
   },
   "source": [
    "One can see how this method of creating circuits is quite powerful. \n",
    "\n",
    "> Note that `cirq.SWAP` is a pre-defined gate in Cirq. We used three `cirq.CNOT`s instead of `cirq.SWAP` in the above example to demonstrate auto-flattening with generators."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "60d8516a19b2"
   },
   "source": [
    "### Insert strategies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "p9LUxAU41wWs"
   },
   "source": [
    "You may have noticed that there is a hole in what we've explained so far. We have been passing a one-dimensional sequence of operations, but the output is a two-dimensional circuit (a list-of-lists-of-operations). There is a degree of freedom that hasn't been account for. Specifically, how does Cirq choose the moment that each operation will be placed within?\n",
    "\n",
    "The answer is the concept of a `cirq.InsertStrategy`. An `InsertStrategy` defines how `Operation`s are placed in a `Circuit` when requested to be inserted at a given location. Here a `location` is identified by the index of the `Moment` in the `Circuit` that operations should be placed before. \n",
    "\n",
    "> *Note*: In the case of `Circuit.append` this means inserting at the index `len(circuit)` which is one more than the largest moment index and so represents the end of the circuit.\n",
    "\n",
    "There are currently four insertion strategies in Cirq:\n",
    "\n",
    "1. `InsertStrategy.EARLIEST` (currently the default),\n",
    "2. `InsertStrategy.NEW`,\n",
    "3. `InsertStrategy.INLINE`,\n",
    "4. `InsertStrategy.NEW_THEN_INLINE`.\n",
    "\n",
    "The strategy `InsertStrategy.EARLIEST` is defined as follows:\n",
    "\n",
    "> `InsertStrategy.EARLIEST`: Scans backward from the insert\n",
    "> location until a moment with operations touching qubits affected by the\n",
    "> operation to insert is found. The operation is added into the moment just\n",
    "> after that location.\n",
    "\n",
    "For example, if we first create an `Operation` in a single moment,\n",
    "and then use `InsertStrategy.EARLIEST` the `Operation` can slide back to this\n",
    "first `Moment` if there is space."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "wNek1WjpX4MR"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "\n",
      "a: ───@───H───\n",
      "      │\n",
      "b: ───@───H───\n",
      "\n",
      "c: ───H───────\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Appending operations with InsertStrategy.EARLIEST.\"\"\"\n",
    "# Create an empty circuit.\n",
    "circuit = cirq.Circuit()\n",
    "\n",
    "# Append an operation.\n",
    "# Note: InsertStrategy.EARLIEST is used by default if not otherwise specified.\n",
    "circuit.append([cirq.CZ(a, b)])\n",
    "\n",
    "# Append more operations.\n",
    "# Note: InsertStrategy.EARLIEST is used by default if not otherwise specified.\n",
    "circuit.append([cirq.H(a), cirq.H(b), cirq.H(c)])\n",
    "\n",
    "# Display the circuit.\n",
    "print(\"Circuit:\\n\")\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4d93a69cfcb8"
   },
   "source": [
    "After creating the first moment with a `CZ` gate, the second\n",
    "append uses the `InsertStrategy.EARLIEST` strategy. The\n",
    "`H` on ``a`` and ``b`` cannot slide back, while the `H` on ``c`` can and so ends up in the first `Moment`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TcHeZM6qXvbS"
   },
   "source": [
    "While `InsertStrategy.EARLIEST` is the default strategy, the second most important strategy is `InsertStrategy.NEW_THEN_INLINE`, defined as follows:\n",
    "\n",
    "> `InsertStrategy.NEW_THEN_INLINE`: For the first operation, add it to a new \n",
    "> `Moment` the insertion point.  Attempts to add the operation after the first \n",
    "> operation to insert into the moment just before the desired insert location. \n",
    "> But, if there's already an existing operation affecting any of the qubits\n",
    "> touched by the operation to insert, a new moment is created instead and this \n",
    "> `Moment` is the one that is subsequently used for insertions.\n",
    "\n",
    "To see an example of this strategy, we create a circuit with the same operations but inserting them with a different strategy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "qWVDhLxFYuRp"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "\n",
      "a: ───@───H───\n",
      "      │\n",
      "b: ───@───H───\n",
      "\n",
      "c: ───────H───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Appending operations with InsertStrategy.NEW_THEN_INLINE.\"\"\"\n",
    "# Create an empty circuit.\n",
    "circuit = cirq.Circuit()\n",
    "\n",
    "# Append an operation.\n",
    "circuit.append([cirq.CZ(a, b)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\n",
    "\n",
    "# Append more operations.\n",
    "circuit.append([cirq.H(a), cirq.H(b), cirq.H(c)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\n",
    "\n",
    "# Display the circuit.\n",
    "print(\"Circuit:\\n\")\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "69a53a1f5de2"
   },
   "source": [
    "In contrast to the previous codeblock using `InsertStrategy.EARLIEST`, we see that the three `cirq.H` gates appended after the `cirq.CZ` gate appear in the same moment when we use `InsertStrategy.NEW_THEN_INLINE`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "y9conKPAPn26"
   },
   "source": [
    "### Exercise: Create a circuit\n",
    "\n",
    "Now that you've learned about `InsertStrategy`s, here is an exercise to validate your understanding.  Create, **using the least number of appends**, the following circuit:\n",
    "\n",
    "\n",
    "\n",
    "```\n",
    "a: ───@───H───────────H───H───\n",
    "      │\n",
    "b: ───@───────H───@───H───────\n",
    "                  │\n",
    "c: ───H───────────@───────────\n",
    "```\n",
    "\n",
    "Here imagine that you want exactly the moments indicated by the spacing of the circuit so that there are six moments in this circuit."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KnA4uBkwEw5-"
   },
   "source": [
    "#### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "cellView": "both",
    "id": "jP4VkPeHcjJT"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "\n",
      "a: ───@───H───────────H───H───\n",
      "      │\n",
      "b: ───@───────H───@───H───────\n",
      "                  │\n",
      "c: ───H───────────@───────────\n"
     ]
    }
   ],
   "source": [
    "#@title\n",
    "# Define three qubits.\n",
    "a = cirq.NamedQubit('a')\n",
    "b = cirq.NamedQubit('b')\n",
    "c = cirq.NamedQubit('c')\n",
    "\n",
    "# Get an empty circuit.\n",
    "circuit = cirq.Circuit()\n",
    "\n",
    "# Append these gates using cirq.InsertStrategy.EARLIEST (the default strategy).\n",
    "circuit.append([cirq.CZ(a, b), cirq.H(c), cirq.H(a)])\n",
    "\n",
    "# Append these gates using cirq.InsertStrategy.NEW_THEN_INLINE.\n",
    "circuit.append(\n",
    "    [cirq.H(b), cirq.CZ(b, c), cirq.H(b), cirq.H(a), cirq.H(a)],\n",
    "    strategy=cirq.InsertStrategy.NEW_THEN_INLINE\n",
    ")\n",
    "\n",
    "# Display the circuit.\n",
    "print(\"Circuit:\\n\")\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "X15yPl_KQ20Z"
   },
   "source": [
    "## Simulations of a Circuit\n",
    "\n",
    "Now that we know how to construct `Circuit`s in Cirq, let's see how to simulate them. First we create a simple circuit to simulate in the following cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "V6tZk3qGqBoH"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───X^0.5───@───X^0.5───M───\n",
      "              │           │\n",
      "b: ───X^0.5───@───X^0.5───M───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Get a circuit to simulate.\"\"\"\n",
    "def basic_circuit(measure=True):\n",
    "    \"\"\"Returns a simple circuit with some one- and two-qubit gates,\n",
    "    as well as (optionally) measurements.\n",
    "    \"\"\"\n",
    "    # Gates we will use in the circuit.\n",
    "    sqrt_x = cirq.X**0.5\n",
    "    cz = cirq.CZ\n",
    "    \n",
    "    # Yield the operations.\n",
    "    yield sqrt_x(a), sqrt_x(b)\n",
    "    yield cz(a, b)\n",
    "    yield sqrt_x(a), sqrt_x(b)\n",
    "    if measure:\n",
    "        yield cirq.measure(a,b)\n",
    "\n",
    "# Create a circuit including measurements.\n",
    "circuit = cirq.Circuit(basic_circuit())\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WpywVOeDqi4Q"
   },
   "source": [
    "The main simulator in Cirq is the `cirq.Simulator`. The general pattern of simulation is to instantiate this simulator, then pass in a circuit to either the `run` or `simulate` methods (more on this below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "id": "KmGuMjvGw_Ef"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measurement results:\n",
      "a,b=0, 1\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Example of simulating a circuit in Cirq.\"\"\"\n",
    "# Get a simulator.\n",
    "simulator = cirq.Simulator()\n",
    "\n",
    "# Pass the circuit to the simulator.run method.\n",
    "result = simulator.run(circuit, repetitions=1)\n",
    "print(\"Measurement results:\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aHugx9T0z047"
   },
   "source": [
    "Running this multiple times should result in different measurement results, since the circuit produces a superposition over all computational basis states."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "416e9c012263"
   },
   "source": [
    "Above we used the `run` method of the `simulator`. In Cirq, `run` methods mimic the actual hardware in that they don't give one access to unphysical objects like the wavefunction. The `repetitions` argument is how many times to sample from the circuit.\n",
    "\n",
    "If one wants to get the wavefunction, the `simulate` methods can be used as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "Apj7WiFZ0WFm"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wavefunction:\n",
      "[0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n",
      "\n",
      "Dirac notation:\n",
      "0.5|00⟩ + 0.5j|01⟩ + 0.5j|10⟩ + 0.5|11⟩\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulating a circuit with the `simulate` method.\"\"\"\n",
    "# Get a circuit without measurements.\n",
    "circuit = cirq.Circuit(basic_circuit(measure=False))\n",
    "\n",
    "# Simulate the circuit.\n",
    "result = simulator.simulate(circuit, qubit_order=[a, b])\n",
    "\n",
    "# Print the final state vector (wavefunction).\n",
    "print(\"Wavefunction:\")\n",
    "print(np.around(result.final_state_vector, 3))\n",
    "\n",
    "# Print the wavefunction in Dirac notation.\n",
    "print(\"\\nDirac notation:\")\n",
    "print(result.dirac_notation())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "t18-sIJc0cvf"
   },
   "source": [
    "Notice that we passed a `qubit_order` into the `simulate` method.  This order helps define the order of the kronecker (tensor) product used in the resulting `final_state_vector`.  \n",
    "\n",
    "> *Note*: The `qubit_order` argument is optional. When it is omitted, qubits are sorted ascending according to the ordering methods defined by their Python class (for example `cirq.NamedQubit` sorts lexicographically by name).\n",
    "If there are multiple types of qubits in one circuit, the name of the type is used as a tie breaker.\n",
    "\n",
    "The simplest `qubit_order` value you can provide is a list of the qubits in the desired order. Any qubits from the circuit that are not in the list will be ordered using the  default `__str__` ordering, but come after qubits that are in the list. \n",
    "\n",
    "> **Note**: Be aware that all qubits in the list are included in the simulation, even if they are not operated on by the circuit.\n",
    "\n",
    "The mapping from the order of the qubits to the order of the  amplitudes in the wave function can be tricky to understand.  Basically, it is the same as the ordering used by `numpy.kron`.\n",
    "\n",
    "> If the wavefunction is the array \n",
    ">> (0.1, 0.2, 0.3, 0.4),\n",
    "\n",
    "> then this is \n",
    ">> 0.1|00⟩ + 0.2|01⟩ + 0.3|10⟩ + 0.4|11⟩ \n",
    "\n",
    "> in Dirac notation. If \n",
    ">> qubit order = [a, b]\n",
    "\n",
    "> then |00> means qubit a is in 0 and qubit b is in 0, |01> means \n",
    "> qubit a is 0 and qubit b is 1, etc.\n",
    "\n",
    "Another way to think about the qubit-to-amplitude ordering is as \"for loop ordering\":\n",
    "\n",
    "```\n",
    "for a in [0, 1]:\n",
    "    for b in [0, 1]:\n",
    "        print(a, b)\n",
    "```\n",
    "\n",
    "The first index (the outermost loop) is the slowest to vary."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "YLpiz0aN1Jd6"
   },
   "source": [
    "### Repetitions and histograms\n",
    "\n",
    "As mentioned, the simulator `run` methods also take an option for repeating the circuit, namely, the `repetitions` argument. If the measurements in the circuit are terminal and all other operations are unitary, this simulator is optimized to not recompute the wavefunction before sampling from the circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "QxkmBlo21lrQ"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({1: 261, 3: 256, 2: 248, 0: 235})\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate a circuit using 1000 repetitions.\"\"\"\n",
    "# Get a circuit with terminal measurements to simulate.\n",
    "circuit = cirq.Circuit(basic_circuit())\n",
    "\n",
    "# Sample from the circuit 1000 times.\n",
    "result = simulator.run(circuit, repetitions=1000)\n",
    "\n",
    "# Get a histogram of measurement results.\n",
    "print(result.histogram(key=\"a,b\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bD0zX0zP2HxQ"
   },
   "source": [
    "Here we have also demonstrated the use of the `histogram` method on the `result` which sums over all the different results for all of the different repetitions.\n",
    "\n",
    "The `histogram` method can also be given a `fold_func` argument, in order to group measurement results under some key before counting them up.\n",
    "For example, we can group by whether or not the two measurement results agreed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "id": "rPqVUsD9snYf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'disagree': 509, 'agree': 491})\n"
     ]
    }
   ],
   "source": [
    "print(result.histogram(key=\"a,b\", fold_func=lambda bits: \"agree\" if bits[0] == bits[1] else \"disagree\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qFsytBIbOVD8"
   },
   "source": [
    "## The Deutsch-Jozsa Algorithm\n",
    "\n",
    "The very first indication that quantum computers could be more powerful than classical computers was provided by David Deutsch in his 1985 paper\n",
    "\n",
    "> David Deutsch,  \"[Quantum Theory, the Church-Turing Principle and the Universal Quantum Computer](https://people.eecs.berkeley.edu/~christos/classics/Deutsch_quantum_theory.pdf)\" *Proc. R. Soc. Lond.* A **400** 97–117. http://doi.org/10.1098/rspa.1985.0070\n",
    "\n",
    "This algorithm was extended by Deutsch and Richard Jozsa to a more convincing algorithmic seperation and what is now called the Deutsch-Jozsa algorithm.  In this section we will show how to write circuits for the Deutsch algorithm and then as an exercise in using Cirq for algorithms for a small version of the Deutsch-Jozsa algorithm.\n",
    "\n",
    "Let's begin with the Deutsch algorithm.  In Deutsch's algorithm you are given access to a box which computes a one bit boolean function.  That is it is a box which takes in a bit and outputs a bit.  If we want to be a mathematician or theoretical computer scientist we write the function $f$ as $f: \\{0, 1\\} \\rightarrow \\{0, 1\\}$.  There are exactly four such boolean functions which we can write out in a table\n",
    "\n",
    "| $x$ | $f_0$ | $f_1$ | $f_x$ | $f_{\\bar{x}}$ |\n",
    "| --- |  --- | --- | --- | --- |\n",
    "| 0 | 0 | 1 | 0 | 1\n",
    "| 1 | 0 | 1 | 1 | 0\n",
    "\n",
    "The first two of these are *constant* functions, $f_0$ and $f_1$.  That is they always output a constant value (independent of the input).  The other two $f_x$ and $f_\\bar{x}$ are *balanced*.  Over their inputs $0$ and $1$, they have an equal number of $0$s and $1$s in their truth table.  \n",
    "\n",
    "We can now state Deutsch's problem:\n",
    "\n",
    "> Given access to a one bit input one bit output boolean function, determine by querying the function whether the function is *balanced* or *constant*.\n",
    "\n",
    "It shouldn't take you much to convince yourself that in order to solve this problem classically you need to call the function on both possible input values.  The easiest way to see this is just to consider what happens if you query the function on one particular input and notice that, for either input, learning the value of the function does not separate the constant from balanced functions. In summary:\n",
    "\n",
    "*Classically one must query the binary function twice to distinguish the constant function from the balanced function.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UAec5ZBuSWYU"
   },
   "source": [
    "Now lets turn to the quantum approach to this problem.  There is one bit of book keeping we need to take care of.  Above we have described a classical function on bits that is not reversible.  That is, knowing the values of the output does not allow us to determine uniquely the value of the input.  In order to run this on a quantum computer, however we need to make this computation reversible.  A trick for taking a classical non-reversible function and making it \"quantum happy\" is to compute the value in an extra register and store the input.  Suppose we have an $n$ bit input $x$ and we are computing a (potentially non-reverisble) boolean function $f(x)$.  Then we can implement this via a Unitary $U_f$ that acts like on $n + 1$ qubits\n",
    "\n",
    "$$\n",
    "U_f |x\\rangle |y\\rangle = |x\\rangle | y \\oplus f(x)\\rangle .\n",
    "$$\n",
    "\n",
    "Here $\\oplus$ is addition modulo $2$ (XOR) and we have identified how $U_f$ acts by its action on all computational basis states $|x\\rangle$ ($n$ input qubits) and $|y\\rangle$ ($1$ output qubit). To see that this is reversible one can note that applying the transformation twice returns the state to its original form.\n",
    "\n",
    "Let's see how to implement these functions in Cirq.\n",
    "\n",
    "$f_0$ enacts the transform\n",
    "$$\n",
    "\\begin{eqnarray}\n",
    "|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n",
    "|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n",
    "|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n",
    "|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n",
    "\\end{eqnarray}\n",
    "$$\n",
    "Well this is just the identity transform, i.e. an empty circuit.\n",
    "\n",
    "$f_1$ enacts the transform\n",
    "$$\n",
    "\\begin{eqnarray}\n",
    "|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n",
    "|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n",
    "|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n",
    "|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n",
    "\\end{eqnarray}\n",
    "$$\n",
    "This is the `cirq.X` bit flip gate on the second qubit.\n",
    "\n",
    "$f_x$ enacts the transform\n",
    "$$\n",
    "\\begin{eqnarray}\n",
    "|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n",
    "|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n",
    "|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n",
    "|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n",
    "\\end{eqnarray}\n",
    "$$\n",
    "This is nothing more than a `cirq.CNOT` from the first bit to the second bit.\n",
    "\n",
    "Finally $f_\\bar{x}$ enacts the transform\n",
    "$$\n",
    "\\begin{eqnarray}\n",
    "|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n",
    "|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n",
    "|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n",
    "|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n",
    "\\end{eqnarray}\n",
    "$$\n",
    "which is a `cirq.CNOT` from the first bit to the second bit followed by a `cirq.X` on the second bit.\n",
    "\n",
    "We can encapulate these functions into a dictionary from a oracle name to the operations in the circuit needed to enact this function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "id": "YtWiBHonly69"
   },
   "outputs": [],
   "source": [
    "\"\"\"Store the operations to query each function in a dictionary.\"\"\"\n",
    "# Get qubits for the operations to act on.\n",
    "q0, q1 = cirq.LineQubit.range(2)\n",
    "\n",
    "# Define the dictionary of operations. The key of each dictionary entry\n",
    "# is the subscript of the function f in the above explanatory text.\n",
    "oracles = {\n",
    "    '0': [],\n",
    "    '1': [cirq.X(q1)],\n",
    "    'x': [cirq.CNOT(q0, q1)],\n",
    "    'notx': [cirq.CNOT(q0, q1), cirq.X(q1)]\n",
    "}    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "axCSYj3EmAEo"
   },
   "source": [
    "We now turn to Deutch's algorithm.  Suppose we are given access to the reversible oracle functions we have defined above.  By a similar argument for our irreversible classical functions you can show that you cannot distinguish the balanced from the constant functions by using this oracle only once.  But now we can ask the question: what if we are allowed to query this box in superposition, i.e. what if we can use the power of quantum computing?\n",
    "\n",
    "Deutsch was able to show that you could solve this problem now, with quantum computers, using only a single query.  To see how this works we need two simple insights.\n",
    "\n",
    "Suppose that we prepare the second qubit in the superposition state $|-\\rangle=\\frac{1}{\\sqrt{2}}(|0\\rangle-|1\\rangle)$ and apply the oracle.  Then we can check that\n",
    "$$ \n",
    "U_f |x\\rangle |-\\rangle = U_f|x\\rangle \\frac{1}{\\sqrt{2}}(|0\\rangle -|1\\rangle ) = |x\\rangle \\frac{1}{\\sqrt{2}}(|f(x)\\rangle -|f(x) \\oplus 1\\rangle ) =  (-1)^{f(x)} |x\\rangle |-\\rangle .\n",
    "$$  \n",
    "This is the so called \"phase kickback trick\".  By applying $U_f$ onto a target which is in superposition, the value of the function ends up showing up in the global phase.  \n",
    "\n",
    "How can we leverage this to distinguish between the constant and balanced functions?  Note that for the constant functions the phase that is applied is the same for all inputs $|x\\rangle$, whereas for the balanced functions the phase is different for each value of $x$.  In other words, if we use the phase kickback trick then for each of the oracles we apply the following transform on the first qubit:\n",
    "\n",
    "$$\n",
    "\\begin{eqnarray}\n",
    "f_0 \\rightarrow I, &&\n",
    "f_1 \\rightarrow -I, &&\n",
    "f_x \\rightarrow Z, &&\n",
    "f_\\bar{x} \\rightarrow -Z &&\n",
    "\\end{eqnarray}\n",
    "$$\n",
    "\n",
    "Now we only need, on the first qubit, to distinguish between the identity gate and the $Z$ gate.  But we can do this by recalling the identity\n",
    "\n",
    "$$ \n",
    "H Z H = X\n",
    "$$\n",
    "\n",
    "where $H$ is the Hamadard gate.\n",
    "\n",
    "This means that we can turn a phase flip into a bit flip by applying Hadamards before and after the phase flip.  If we look at the constant and balanced functions we see that this means that the constant functions will be proportional to $I$ and the balanced functions will be proportional to $X$.  If we feed in $|0\\rangle$ to this register, then in the first cases we will only see $|0\\rangle$ and in the second case we will only see $|1\\rangle$.  In other words we will be able to distinguish constant from balanced using a single query of the oracle.\n",
    "\n",
    "Let's code this up."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "id": "aMHzLxztj-gq"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit for f_0:\n",
      "0: ───H───H───M───\n",
      "\n",
      "1: ───X───H───────\n",
      "\n",
      "Circuit for f_1:\n",
      "0: ───H───H───M───\n",
      "\n",
      "1: ───X───H───X───\n",
      "\n",
      "Circuit for f_x:\n",
      "0: ───H───────@───H───M───\n",
      "              │\n",
      "1: ───X───H───X───────────\n",
      "\n",
      "Circuit for f_notx:\n",
      "0: ───H───────@───H───M───\n",
      "              │\n",
      "1: ───X───H───X───X───────\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Creating the circuit used in Deutsch's algorithm.\"\"\"\n",
    "def deutsch_algorithm(oracle):\n",
    "    \"\"\"Returns the circuit for Deutsch's algorithm given an input\n",
    "    oracle, i.e., a sequence of operations to query a particular function.\n",
    "    \"\"\"\n",
    "    yield cirq.X(q1)\n",
    "    yield cirq.H(q0), cirq.H(q1)\n",
    "    yield oracle\n",
    "    yield cirq.H(q0)\n",
    "    yield cirq.measure(q0)\n",
    "\n",
    "for key, oracle in oracles.items():\n",
    "    print(f\"Circuit for f_{key}:\")\n",
    "    print(cirq.Circuit(deutsch_algorithm(oracle)), end=\"\\n\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Zy-2ysxzweyv"
   },
   "source": [
    "Lets run these circuits a bunch of times to see that the measurement result ends up correctly distinguishing constant from balanced."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "id": "ImffrBgJvLme"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "oracle: f_0    results: 0=0000000000\n",
      "oracle: f_1    results: 0=0000000000\n",
      "oracle: f_x    results: 0=1111111111\n",
      "oracle: f_notx results: 0=1111111111\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate each of the circuits.\"\"\"\n",
    "simulator = cirq.Simulator()\n",
    "for key, oracle in oracles.items():\n",
    "    result = simulator.run(cirq.Circuit(deutsch_algorithm(oracle)), \n",
    "                          repetitions=10)\n",
    "    print('oracle: f_{:<4} results: {}'.format(key, result))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "845af7bfc7d6"
   },
   "source": [
    "We interpret the simulation results as follows:\n",
    "\n",
    "- For the first two functions $f_0$ and $f_1$, we always measure $0$. Therefore, we know that these functions are constant.\n",
    "- For the second two functions $f_x$ and $f_{\\bar{x}}$, we always measure $1$. Therefore, we know that these functions are balanced."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5edb6fe11163"
   },
   "source": [
    "### Exercise: Two Bit Deutsch-Jozsa Algorithm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "v4ka34Kuj4K0"
   },
   "source": [
    "All boolean functions for one input bit are either constant or balanced.  For boolean functions from two input bits not all functions are constant or balanced.  There are two constant functions, $f(x_0, x_1) = 0$ and $f(x_0, x_1)=1$, while there are ${4 \\choose 2} = 6$ balanced functions.  The following code gives you the operations for these functions where we take two input qubits and compute the function in the third qubit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "id": "V5ZCXGCrxl4k"
   },
   "outputs": [],
   "source": [
    "\"\"\"Operations to query all possible functions on two bits.\n",
    "Two of these functions are constant, and six of these functions are balanced.\n",
    "\"\"\"\n",
    "# Define three qubits to use.\n",
    "q0, q1, q2 = cirq.LineQubit.range(3)\n",
    "\n",
    "# Define the operations to query each of the two constant functions.\n",
    "constant = (\n",
    "    [], \n",
    "    [cirq.X(q2)]\n",
    ")\n",
    "\n",
    "# Define the operations to query each of the six balanced functions.\n",
    "balanced = (\n",
    "    [cirq.CNOT(q0, q2)], \n",
    "    [cirq.CNOT(q1, q2)], \n",
    "    [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2)],\n",
    "    [cirq.CNOT(q0, q2), cirq.X(q2)], \n",
    "    [cirq.CNOT(q1, q2), cirq.X(q2)], \n",
    "    [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2), cirq.X(q2)]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mr9ltXSJyB79"
   },
   "source": [
    "An extension of Deutsch's orginal algorithm is the Deutsch-Jozsa algorithm, which can distinguish constant from balanced functions like these using a single query to the oracle.  **The goal of this exercise** is to write a quantum circuit that can distinguish these."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "id": "qJP_e68e1JBs"
   },
   "outputs": [],
   "source": [
    "\"\"\"Exercise: Write a quantum circuit that can distinguish \n",
    "constant from balanced functions on two bits.\n",
    "\"\"\"\n",
    "def your_circuit(oracle):\n",
    "    # Your code here!\n",
    "    yield oracle\n",
    "    # Your code here!\n",
    "    yield cirq.measure(q2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3e75a276e239"
   },
   "source": [
    "You can check your circuit by running the follow cell which simulates the circuit for all oracles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "id": "81da6ec6fc5a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Your result on constant functions:\n",
      "2=0000000000\n",
      "2=1111111111\n",
      "\n",
      "Your result on balanced functions:\n",
      "2=0000000000\n",
      "2=0000000000\n",
      "2=0000000000\n",
      "2=1111111111\n",
      "2=1111111111\n",
      "2=1111111111\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Check your answer by running this cell.\"\"\"\n",
    "simulator = cirq.Simulator()\n",
    "    \n",
    "print(\"\\nYour result on constant functions:\")\n",
    "for oracle in constant:\n",
    "    result = simulator.run(cirq.Circuit(your_circuit(oracle)), repetitions=10)\n",
    "    print(result)\n",
    "    \n",
    "print(\"\\nYour result on balanced functions:\")\n",
    "for oracle in balanced:\n",
    "    result = simulator.run(cirq.Circuit(your_circuit(oracle)), repetitions=10)\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "L6vfs97CFZB2"
   },
   "source": [
    "#### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "cellView": "both",
    "id": "mUvm9rmRFb4p"
   },
   "outputs": [],
   "source": [
    "#@title\n",
    "def dj_circuit(oracle):\n",
    "    # Phase kickback trick.\n",
    "    yield cirq.X(q2), cirq.H(q2)\n",
    "    \n",
    "    # Get an equal superposition over input bits.\n",
    "    yield cirq.H(q0), cirq.H(q1)\n",
    "    \n",
    "    # Query the function.\n",
    "    yield oracle\n",
    "    \n",
    "    # Use interference to get result, put last qubit into |1>.\n",
    "    yield cirq.H(q0), cirq.H(q1), cirq.H(q2)\n",
    "    \n",
    "    # Use a final OR gate to put result in final qubit.\n",
    "    yield cirq.X(q0), cirq.X(q1), cirq.CCX(q0, q1, q2)\n",
    "    yield cirq.measure(q2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "79348c9be8a9"
   },
   "source": [
    "As above, we can check the solution by running the circuit with each of the oracles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "id": "c1b1e989dab2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Result on constant functions:\n",
      "2=0000000000\n",
      "2=0000000000\n",
      "\n",
      "Result on balanced functions:\n",
      "2=1111111111\n",
      "2=1111111111\n",
      "2=1111111111\n",
      "2=1111111111\n",
      "2=1111111111\n",
      "2=1111111111\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate the Deutsch-Jozsa circuit and check the results.\"\"\"\n",
    "print(\"Result on constant functions:\")\n",
    "for oracle in constant:\n",
    "    result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n",
    "    print(result)\n",
    "    \n",
    "print(\"\\nResult on balanced functions:\")\n",
    "for oracle in balanced:\n",
    "    result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2d62c4a01340"
   },
   "source": [
    "As with the single-bit case (Deutsch's algorithm), we always measure $0$ for constant functions and always measure $1$ for balanced functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mmhbPIhT4YAI"
   },
   "source": [
    "## Gates"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "F5ubTic94X79"
   },
   "source": [
    "Cirq comes with a plethora of common gates.  Here we show a few of them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "id": "iIpoDaqK4yjV"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0: ───X───@───H───────@───×───@───@───iSwap──────Rx(0.5π)───X^0.5───\n",
      "          │           │   │   │   │   │\n",
      "1: ───Y───@───@───T───@───×───×───@───iSwap──────Ry(0.5π)───────────\n",
      "              │       │       │   │\n",
      "2: ───Z───────X───S───@───────×───X───Rz(0.5π)──────────────────────\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Examples of common gates defined in Cirq.\"\"\"\n",
    "# Get some qubits.\n",
    "q0, q1, q2 = cirq.LineQubit.range(3)\n",
    "\n",
    "# Get a bunch of common gates defined in Cirq.\n",
    "ops = [\n",
    "    cirq.X(q0),                # Pauli-X.\n",
    "    cirq.Y(q1),                # Pauli-Y.\n",
    "    cirq.Z(q2),                # Pauli-Z.\n",
    "    cirq.CZ(q0,q1),            # Controlled-Z gate.\n",
    "    cirq.CNOT(q1,q2),          # Controlled-X gate.\n",
    "    cirq.H(q0),                # Hadamard gate.\n",
    "    cirq.T(q1),                # T gate.\n",
    "    cirq.S(q2),                # S gate.\n",
    "    cirq.CCZ(q0, q1, q2),      # Controlled CZ gate.\n",
    "    cirq.SWAP(q0, q1),         # Swap gate.\n",
    "    cirq.CSWAP(q0, q1, q2),    # Controlled swap gate.\n",
    "    cirq.CCX(q0, q1, q2),      # Toffoli (CCNOT) gate.\n",
    "    cirq.ISWAP(q0, q1),        # ISWAP gate.\n",
    "    cirq.rx(0.5 * np.pi)(q0),  # Rotation about X.\n",
    "    cirq.ry(0.5 * np.pi)(q1),  # Rotation about Y.\n",
    "    cirq.rz(0.5 * np.pi)(q2),  # Rotation about Z.\n",
    "    cirq.X(q0) ** 0.5,         # Sqrt of NOT gate.\n",
    "]\n",
    "\n",
    "# Display a circuit with all of these operations.\n",
    "print(cirq.Circuit(ops))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FKRGtncT7R0v"
   },
   "source": [
    "For each of these gates, you can figure out how they act on the computational basis by calling `cirq.unitary` on the gate.  For example, to see the unitary of `CNOT`, we can do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "id": "7SUAT5F17afR"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
      " [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n",
      " [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n",
      " [0.+0.j 0.+0.j 1.+0.j 0.+0.j]]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Get the unitary of CNOT.\"\"\"\n",
    "print(cirq.unitary(cirq.CNOT))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "flm4CcqT2DoI"
   },
   "source": [
    "For single qubit gates, we have named gates like `cirq.H` for the Hadmard gate as well as the single qubit rotation gates defined as follows.\n",
    "\n",
    "$$ \n",
    "{\\tt cirq.rx(θ)}: \\exp(-i \\theta X) = cos \\theta I - i \\sin \\theta X =\\left[ \\begin{array} ~\\cos \\theta & -i \\sin \\theta \\\\ -i \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n",
    "$$ \n",
    "$$ \n",
    "{\\tt cirq.ry(θ)}: \\exp(-i \\theta Y) = cos \\theta I - i \\sin \\theta Y =\\left[ \\begin{array} ~\\cos \\theta &  -\\sin \\theta \\\\  \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n",
    "$$ \n",
    "$$ \n",
    "{\\tt cirq.rz(θ)}: \\exp(-i \\theta Z) = cos \\theta I - i \\sin \\theta Z =\\left[ \\begin{array} ~e^{i \\theta} & 0 \\\\ 0 & e^{-i \\theta} \\end{array} \\right] \\\\\n",
    "$$ \n",
    "\n",
    "In addition to `cirq.unitary` another important method (behind the scenes, anyways) is `cirq.apply_unitary`.  This allows you to apply a unitary gate onto a state.  Of course we could have applied the unitary directly to the state, using `cirq.unitary`.   We'll see below in understanding how these methods are implemented that the `cirq.apply_unitary` can be used to apply the gate more directly onto the state and can save allocations of memory to store the unitary.  \n",
    "\n",
    "If we apply `cirq.rx` to a state we can see how it rotates the state.  To do this let us introduce a new simulate method `simulate_moment_steps`.  This allows us to simulate the circuit `Moment` by `Moment`.  At each point we can access the state.  For example here we can use this to create a circuit that is a series of small `cirq.rx` rotations and plot the probablility of measuring the state in the $|0\\rangle$ state:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "id": "UgoNBN1H8B6h"
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEDCAYAAAA2k7/eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8vihELAAAACXBIWXMAAAsTAAALEwEAmpwYAAAxmklEQVR4nO2dfVxUZdrHfwMMAoIiBqZDZlkpARb4sqam5qKEmuFLSiupu5a12YuJkbomluJrurtk++w+5larrJLEErlt9KQ+bSViIagQ2qN+JBxdhQCVN2HwPH/QjAycM4cZ5sycc9/X9/PxI3OGOXPd1/07F+fc93Vft04QBAEEQRAE83i42wCCIAjCNVDAJwiC4AQK+ARBEJxAAZ8gCIITKOATBEFwAgV8giAITvBytwG2KCgocLcJBEEQmmTo0KEdjqk64APiRneG0tJShIWFOdmarkN22Y9abSO77EOtdgHqtc1Ru6RulmlIhyAIghMo4BMEQXACBXyCIAhOoIBPEATBCYoG/B9++AExMTHYvXt3h/cOHz6MWbNmYc6cOXjnnXeUNIMgCIKAglk69fX1WLt2LR566CHR99etW4edO3eiT58+SExMRGxsLO65554uf292oRFbck/jYk0D+gVewquxgxAfZejyeQm+yS40Yk1OCWoamgEAHjrgpgAYSGOEk2ivsV5+ejw9NBDOTB5SLOB7e3tjx44d2LFjR4f3ysvL0bNnT/Tt2xcAMG7cOOTl5XU54GcXGrEi6yQamlsAAMaaBizJKMKSjCIYAn3pwiTsov0F2JabPxcVJ40RXcGWxqrrm/H7bypg6Gd0mqYUG9Lx8vKCj4+P6HsVFRUICgqyvA4KCkJFRUWXv3NL7mlLsG+PsaYBK7JOIrvQ2OXvIdgnu9CIV/cdF70Qp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IKBEEQnMDUkA5BEAQhDQV8giAITqCATxAEwQkU8AmCIDiBAj5BEAQnMJWWSRDOID09HR9//DG8vb3R2NiIpUuXIigoCN26dVM0J5sglIYCPkG04cKFC/jwww+RmZkJvV6P8+fPY9WqVfjFL36BiIgICviEpqGATxBtqK2txY0bN9Dc3Ay9Xo8BAwbg9ddfx29+8xsEBQWhd+/eaGpqwrZt2+Dl5YW+ffti7dq1KCwsxI4dO+Dt7Y2LFy8iNjYWv/3tb93dHIKwggI+QbRh8ODBGDJkCH75y19i3LhxGDt2LCZNmoSHH34YsbGxGDJkCOLj4/H+++8jMDAQmzdvxmeffYY+ffqguLgYBw4cgJeXF+Li4pCQkGBVvZUg3A0FfIJox+bNm3H27Fl89dVXePfdd7Fnzx7069cPQGvp3LKyMkt5h/r6evTq1Qt9+vTBAw88gO7duwMA7r33XpSXl1PAJ1QFBXyCaIMgCGhqasLAgQMxcOBAPPXUU4iLi7O8r9frERISgl27dll9Lj8/Hzdv3rQ6D0GoDUrLJIg2ZGZm4vXXX7cE7OvXr+PmzZsIDQ1FS0sLevbsCaB1AxkA2LVrF06dOgUA+P7779HQ0IAbN27gzJkzGDBggFvaQBBSUPE0gmhDS0sL3nrrLXz77bfw8/ODyWTCokWL8NNPP+Htt9/Ghg0boNfrsWnTJsvd/ubNm1FYWIh33nkHvXv3xvnz5xEXF4dFixa5uzkEYQUFfIJwAvn5+UhPT0daWpq7TSEISWhIhyAIghPoDp8gCIIT6A6fIAiCEyjgEwRBcAIFfIIgCE6ggE8QBMEJFPAJgiA4gQI+QRAEJ/w/rxVbHCL5+VIAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\"\"\"Plot the probability of measuring a qubit in the ground state.\"\"\"\n",
    "# Get a qubit.\n",
    "a = cirq.NamedQubit('a')\n",
    "\n",
    "# Get a circuit of a bunch of X rotations.\n",
    "circuit = cirq.Circuit([cirq.rx(np.pi / 50.0)(a) for theta in range(200)])\n",
    "\n",
    "# List to store probabilities of the ground state.\n",
    "probs = []\n",
    "\n",
    "# Step through the simulation results.\n",
    "for step in simulator.simulate_moment_steps(circuit):\n",
    "    prob = np.abs(step.state_vector()) ** 2\n",
    "    probs.append(prob[0])\n",
    "\n",
    "# Plot the probability of the ground state at each simulation step.\n",
    "plt.style.use('seaborn-whitegrid')\n",
    "plt.plot(probs, 'o')\n",
    "plt.xlabel(\"Step\")\n",
    "plt.ylabel(\"Probability of ground state\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6q0YkXSZBvzd"
   },
   "source": [
    "Above we have given ourselves direct access to the wave function and calculated the exact probabilities.  Suppose we wanted to sample from the wave function at each point instead.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "id": "iynhJEvoCIro"
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEDCAYAAAA2k7/eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8vihELAAAACXBIWXMAAAsTAAALEwEAmpwYAAA3vklEQVR4nO2de1xU9db/P3uG4SYkYOARzLx0UkJUvGVRaaSSokZlMiqpzzHNJ7tY3tCXhT6lopTnd9DOc85jnupRK47GIcueOK/Ep9PxWgheCO1Rk3D0KCioCMgw7N8fOOPMsPfsmWH2nn1Z739077nstb97zWJ913d912JYlmVBEARBqB6dvwUgCIIgpIEMPkEQhEYgg08QBKERyOATBEFoBDL4BEEQGoEMPkEQhEYI8LcArigpKfG3CARBEIpkyJAh7c7J2uAD3EK7Q0VFBeLj430sTcchuTxHrrKRXJ4hV7kA+crmrVx8zjKFdAiCIDQCGXyCIAiNQAafIAhCI5DBJwiC0AiiGvyff/4Zo0ePxrZt29q9tn//fkyePBkZGRl4//33xRSDIAiCgIhZOg0NDXj77bfx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XyCIAiNQAafIAhCI5DBJwiC0Ahk8AmCIDQCGXyCIAiN8P8BtVBTxRmENGgAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\"\"\"Plot the probability of measuring a qubit in the ground state by sampling.\"\"\"\n",
    "# Number of times to sample.\n",
    "repetitions = 100\n",
    "\n",
    "# List to store the probability of the ground state.\n",
    "sampled_probs = []\n",
    "\n",
    "for i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n",
    "    samples = step.sample([a], repetitions=repetitions)\n",
    "    prob = np.sum(samples, axis=0)[0] / repetitions\n",
    "    sampled_probs.append(prob)\n",
    "    \n",
    "\n",
    "# Plot the probability of the ground state at each simulation step.\n",
    "plt.style.use('seaborn-whitegrid')\n",
    "plt.plot(sampled_probs, 'o')\n",
    "plt.xlabel(\"Step\")\n",
    "plt.ylabel(\"Probability of ground state\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2483adccd339"
   },
   "source": [
    "## Custom gates"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RACz4Z5GDMAf"
   },
   "source": [
    "Supose there is a gate that you want Cirq to support, but it is not implemented in Cirq.  How do you go about adding a new gate?  \n",
    "\n",
    "Cirq tries to be Pythonic.  One way in which it does this is that it relies on Python's **protocol** pattern.  Protocols are similar to interfaces, in that they define a collection of methods that an object must support to implement a protocol, but different in that this requirement is more informal and not a part of a class or interface declaration.  An object supports a protocol if it implements the methods that the protocol defines.  You're probably familiar with this if you've ever done something like defined your own `Container` in Python.  To do this for an object you simply define the `__contains__`, `__setitem__`, and `__getitem__` methods on your object, and then you can use this object anywere the Container protocol is supported.  \n",
    "\n",
    "Let's see how this works for defining a custom gate.  The gate we will define is a single qubit gate that has only rational amplitudes. This is based on the famous 3, 4, 5 triangle you may remember from a long ago math class: $3^2 + 4^2 = 5^2$.  Using this observation we can construct normalized vectors and a unitary transform using the ratios of $3$, $4$, and $5$: \n",
    "$$\n",
    "\\zeta =\\left[ \\begin{array}\n",
    "~\\frac{3}{5} & \\frac{4}{5} \\\\\n",
    "-\\frac{4}{5} & \\frac{3}{5}\n",
    "\\end{array} \\right]\n",
    "$$\n",
    "\n",
    "Below is a simple implementation of this gate in Cirq.  To do this we simply define a class that inherits from `cirq.SingleQubitGate` and implements the `cirq.SupportsUnitary` protocol by implementing the `_unitary_(self)` method.  We also define an optional `__str__` representation which Cirq will use when printing this gate out in a circuit diagram."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "id": "Y2a7t2qmLDTb"
   },
   "outputs": [],
   "source": [
    "\"\"\"Example of defining a custom gate in Cirq.\"\"\"\n",
    "class RationalGate(cirq.SingleQubitGate):\n",
    "    \n",
    "    def _unitary_(self):\n",
    "        return np.array([[3 / 5, 4 / 5], [-4 / 5, 3 / 5]])\n",
    "    \n",
    "    def __str__(self):\n",
    "        return 'ζ'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6d262b57bb0c"
   },
   "source": [
    "We can now use this custom gate just like any other gate in Cirq."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "id": "28f06d1baf9b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───ζ───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Using the custom gate in a circuit.\"\"\"\n",
    "a = cirq.NamedQubit('a')\n",
    "rg = RationalGate()\n",
    "print(cirq.Circuit(rg(a)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3132dcbe8413"
   },
   "source": [
    "We can also get its unitary, as shown below, because the `RationalGate` defines a `_unitary_` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "id": "x9dHKNfgMoyz"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.6  0.8]\n",
      " [-0.8  0.6]]\n"
     ]
    }
   ],
   "source": [
    "print(cirq.unitary(rg))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xmF-uscmPP_G"
   },
   "source": [
    "Let's check that we can use this gate in a simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "id": "_RXBrSQ8PWnu"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 0.6+0.j -0.8+0.j]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate a circuit with a custom gate.\"\"\"\n",
    "circuit = cirq.Circuit(rg(a))\n",
    "simulator = cirq.Simulator()\n",
    "result = simulator.simulate(circuit)\n",
    "print(result.final_state_vector)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9da706cd9038"
   },
   "source": [
    "> *Note on simulating circuits with custom gates.* The `_unitary_` method is extremely inefficient for gates over many qubits. In most cases the method `_apply_unitary_` will be used instead, if it is available.\n",
    "This method allows much more fine grained control on how a unitary is applied to a state, but it is harder to implement, for example because it is expected to use the pre-allocated workspace buffer that was given to it.\n",
    "Almost all of the basic gates we have defined in Cirq have this method implemented. If you need to get performant, custom multi-qubit gates, you should implement a custom `_apply_unitary_` method for such gates."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "y63aDja8R4rc"
   },
   "source": [
    "### Exercise: Custom Controlled Rx gate\n",
    "\n",
    "Recall that the `cirq.rx` gate is a rotation about the $X$ Pauli axis:\n",
    "$$ \n",
    "{\\tt cirq.rx(θ)}: \\exp(-i \\theta X) = cos \\theta I - i \\sin \\theta X =\\left[ \\begin{array} ~\\cos \\theta & -i \\sin \\theta \\\\ -i \\sin \\theta & \\cos \\theta\\end{array} \\right] . \\\\\n",
    "$$ \n",
    "\n",
    "As an exercise, create a two-qubit controlled `cirq.rx` gate defined as follows:\n",
    "$$\n",
    "{\\tt CRx(\\theta)}:\n",
    "\\left[\\begin{array}\n",
    "~1 & 0 & 0 & 0 \\\\\n",
    "0 & 1 & 0 & 0  \\\\\n",
    "0 & 0 & \\cos \\theta & -i \\sin \\theta \\\\\n",
    "0 & 0 & -i \\sin \\theta & \\cos \\theta\n",
    "\\end{array} \\right] .\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "id": "9htgTzqAYHsA"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Define a custom controlled cirq.rx gate here.\"\"\"\n",
    "class CRx(cirq.TwoQubitGate):\n",
    "    def __init__(self, theta):\n",
    "        self.theta = theta\n",
    "\n",
    "    def _unitary_(self):\n",
    "        return np.array([\n",
    "            # Your code here!\n",
    "        ])\n",
    "\n",
    "\n",
    "# Print out its unitary.\n",
    "print(np.around(cirq.unitary(CRx(0.25 * np.pi))))     "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7SoneHQRGeUW"
   },
   "source": [
    "#### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "id": "XaG8n5bdGgf2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
      " [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n",
      " [0.+0.j 0.+0.j 1.+0.j 0.-1.j]\n",
      " [0.+0.j 0.+0.j 0.-1.j 1.+0.j]]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Defining a custom controlled cirq.rx gate.\"\"\"\n",
    "class CRx(cirq.TwoQubitGate):\n",
    "    def __init__(self, theta):\n",
    "        self.theta = theta\n",
    "\n",
    "    def _unitary_(self):\n",
    "        return np.array([\n",
    "            [1, 0, 0, 0],\n",
    "            [0, 1, 0, 0],\n",
    "            [0, 0, np.cos(self.theta), -1j * np.sin(self.theta)],\n",
    "            [0, 0, -1j * np.sin(self.theta), np.cos(self.theta)]\n",
    "        ])\n",
    "    \n",
    "    def _circuit_diagram_info_(self, args):\n",
    "        return '@', 'rx({}π)'.format(self.theta / np.pi)\n",
    "\n",
    "\n",
    "# Print out its unitary.\n",
    "print(np.around(cirq.unitary(CRx(0.25 * np.pi))))    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "af7add86ab34"
   },
   "source": [
    "Note that we also define the `_circuit_diagram_info_` method which tells Cirq how to display the gate in a circuit diagram. The first string in the tuple is the symbol for the top wire, and the second string in the tuple is the symbol for the bottom wire. We can use this in a circuit to see the diagram info as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "id": "a1cd089df7ba"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit diagram:\n",
      "a: ───@───────────\n",
      "      │\n",
      "b: ───rx(0.25π)───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Display a circuit with the custom gate.\"\"\"\n",
    "# Get qubits.\n",
    "a = cirq.NamedQubit('a')\n",
    "b = cirq.NamedQubit('b')\n",
    "\n",
    "# Display the circuit.\n",
    "print('Circuit diagram:')\n",
    "print(cirq.Circuit(CRx(0.25 * np.pi)(a, b)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9W_Vlgpzz0D1"
   },
   "source": [
    "### Gate decompositions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Uun4giev4N8F"
   },
   "source": [
    "In many contexts, the notion of what gate you can apply is defined either by the physical hardware you are running or perhaps by the quantum error correcting code you are working with.  In quantum computing we typically talk about **gate sets** and work with respect to a given gate set.  Cirq supports gate decomposition via the `decompose` protocol.  Below we show how one can construct a gate that can be decomposed into two gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "id": "9G-9_29h09Mx"
   },
   "outputs": [],
   "source": [
    "\"\"\"Example of a custom gate which supports the decompose protocol.\"\"\"\n",
    "class HXGate(cirq.SingleQubitGate):\n",
    "    \n",
    "    def _decompose_(self, qubits):\n",
    "        return cirq.H(*qubits), cirq.X(*qubits)\n",
    "    \n",
    "    def __str__(self):\n",
    "        return 'HX'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1a88ad617867"
   },
   "source": [
    "We can use this gate in a circuit as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "id": "370e8528c762"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───HX───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the gate in a circuit.\"\"\"\n",
    "HX = HXGate()\n",
    "\n",
    "a = cirq.NamedQubit('a')\n",
    "circuit = cirq.Circuit(HX(a))\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "eb4e74261590"
   },
   "source": [
    "The symbol `HX` is a single gate, not a product of two gates. We can decompose the `HXGate` using `cirq.decompose` as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "id": "47ec94cdecf3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───Y^0.5───X───X───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Decompose the gate.\"\"\"\n",
    "print(cirq.Circuit(cirq.decompose(circuit)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RLF1narS66iB"
   },
   "source": [
    "Note that this not only decomposed the `HX` gate into `H` and `X`, it also decomposed `H` into `Y**0.5` and `X`.  In order to decompose only once, one can use `cirq.decompose_once`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "id": "AS-YMmAv6zUg"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───H───X───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Decompose the gate once.\"\"\"\n",
    "print(cirq.Circuit(cirq.decompose_once(HX(a))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sQ5N0UR26G_v"
   },
   "source": [
    "When we define a gate, it is good practice to give a default decomposition in terms of common gates.  However, often you will want to change this decomposition at run time for the specific hardware or context you are working in.  To do this we can define an interceptor function which does this decomposition before falling back to the default."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "id": "0sJ1uY6X7l3t"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"overflow: auto; white-space: pre;\">a: ───Z───Y^0.5───X───</pre>"
      ],
      "text/plain": [
       "a: ───Z───Y^0.5───X───"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"Define a custom decomposer.\"\"\"\n",
    "def my_decompose(op):\n",
    "    if isinstance(op, cirq.GateOperation) and isinstance(op.gate, HXGate):\n",
    "        return cirq.Z(*op.qubits), cirq.H(*op.qubits)\n",
    "\n",
    "# Decompose the circuit according to this custom decomposer.\n",
    "cirq.Circuit(cirq.decompose(HX(a), intercepting_decomposer=my_decompose))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OChSQ05Z06mL"
   },
   "source": [
    "You can also define a predicate that says which gates to keep without decomposing further. This predicate should return `True` for all gates that should not be decomposed further, and `False` for all gates that should be decomposed further.\n",
    "\n",
    "> The default predicate is to only keep gates that cannot be decomposed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "id": "KQ2in0ol05S9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[cirq.H(cirq.NamedQubit('a')), cirq.X(cirq.NamedQubit('a'))]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Define a predicate of which gates to keep without decomposing.\"\"\"\n",
    "def keep_h_and_x(op):\n",
    "    return isinstance(op, cirq.GateOperation) and op.gate in [cirq.H, cirq.X]\n",
    "\n",
    "\n",
    "# Decompose the HXGate using a custom predicate for which gates to not decompose.\n",
    "print(cirq.decompose(HX(a), keep=keep_h_and_x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e7486a8ea9d1"
   },
   "source": [
    "In this case, we see that neither `H` nor `X` have been decomposed, as we have specified in `keep_h_and_x`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3HtlMxa6QpVo"
   },
   "source": [
    "## Parameterized Circuits\n",
    "\n",
    "In addition to circuit gates with fixed values, Cirq also supports parameterized gates with symbolic values via `sympy`. These are placeholder values, such as `sympy.Symbol('x')`, that will only be resolved at *run-time*. For simulators these values are resolved by providing a `ParamResolver`.  A `ParamResolver` provides a map from the `Symbol`'s name to its assigned value.  \n",
    "\n",
    "> Plain Python dictionaries can also be used whenever a `ParamResolver` is needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "id": "0afe36a32636"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit with parameterized gates:\n",
      "\n",
      "a: ───X^s───\n",
      "\n",
      "b: ───X^s───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Define a circuit with parameterized gates.\"\"\"\n",
    "# Import sympy for parameterized values.\n",
    "import sympy as sp\n",
    "\n",
    "# Get qubits to use in the circuit.\n",
    "a = cirq.NamedQubit(\"a\")\n",
    "b = cirq.NamedQubit(\"b\")\n",
    "\n",
    "# Define a parameterized value.\n",
    "val = sp.Symbol(\"s\")\n",
    "\n",
    "# Create a circuit.\n",
    "circuit = cirq.Circuit(cirq.X.on(a) ** val, cirq.X.on(b) ** val)\n",
    "\n",
    "# Display it.\n",
    "print(\"Circuit with parameterized gates:\\n\")\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "c67ac3447a5f"
   },
   "source": [
    "When we simulate this circuit, we must provide a `param_resolver` as mentioned."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "id": "TIaVRzCD4deU"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s=0: [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
      "\n",
      "s=1: [ 0.6 +0.6j   0.25-0.25j  0.25-0.25j -0.1 -0.1j ]\n",
      "\n",
      "s=2: [0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n",
      "\n",
      "s=3: [-0.1 +0.1j   0.25+0.25j  0.25+0.25j  0.6 -0.6j ]\n",
      "\n",
      "s=4: [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\n",
    "simulator = cirq.Simulator()\n",
    "\n",
    "# Simulate the circuit for several values of the parameter.\n",
    "for y in range(5):\n",
    "    result = simulator.simulate(circuit, param_resolver={\"s\": y / 4.0})\n",
    "    print(\"s={}: {}\\n\".format(y, np.around(result.final_state_vector, 2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1_2i73Oo4aM1"
   },
   "source": [
    "Here we see that the `Symbol` is used in two gates, and then the resolver provides this value at run time.\n",
    "\n",
    "Parameterized values are most useful in defining what we call a `Study`.  A `Study` is a collection of trials, where each  trial is a run with a particular set of configurations and which may be run repeatedly.  Running a study returns a list of `TrialResult`s per set of fixed parameter values and repetitions.  Example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "id": "Gj_Y3Lrh49o9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "params: OrderedDict([('s', 0.0)])\n",
      "a=0000000000\n",
      "b=0000000000\n",
      "\n",
      "params: OrderedDict([('s', 0.125)])\n",
      "a=0000000000\n",
      "b=0000000000\n",
      "\n",
      "params: OrderedDict([('s', 0.25)])\n",
      "a=0000000000\n",
      "b=1001000000\n",
      "\n",
      "params: OrderedDict([('s', 0.375)])\n",
      "a=1110101001\n",
      "b=0001000100\n",
      "\n",
      "params: OrderedDict([('s', 0.5)])\n",
      "a=0000010011\n",
      "b=0100111101\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\n",
    "# Get a list of param resolvers.\n",
    "resolvers = [cirq.ParamResolver({'s': y / 8.0}) for y in range(5)]\n",
    "\n",
    "# Add measurements to the circuit.\n",
    "circuit.append([cirq.measure(a), cirq.measure(b)])\n",
    "\n",
    "# Simulate the circuit using run_sweep.\n",
    "results = simulator.run_sweep(\n",
    "    program=circuit,\n",
    "    params=resolvers,\n",
    "    repetitions=10\n",
    ")\n",
    "\n",
    "for i, result in enumerate(results):\n",
    "    print('params: {}\\n{}\\n'.format(result.params.param_dict, result))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "av09E7pH44YO"
   },
   "source": [
    "Above we passed in a list of `ParamResolver`s to the `params` parameter of `run_sweep`.  But one can also pass in a `Sweepable`.  There are some useful methods for generating `Sweepable`s, for example to generate an equally spaced set of param resolvers one can use `Linspace`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "id": "zOymGxlb72Fk"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cirq.ParamResolver({'x': 0.0})\n",
      "cirq.ParamResolver({'x': 0.1})\n",
      "cirq.ParamResolver({'x': 0.2})\n",
      "cirq.ParamResolver({'x': 0.3})\n",
      "cirq.ParamResolver({'x': 0.4})\n",
      "cirq.ParamResolver({'x': 0.5})\n",
      "cirq.ParamResolver({'x': 0.6})\n",
      "cirq.ParamResolver({'x': 0.7})\n",
      "cirq.ParamResolver({'x': 0.8})\n",
      "cirq.ParamResolver({'x': 0.9})\n",
      "cirq.ParamResolver({'x': 1.0})\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Alternative method of getting a sequence of param resolvers.\"\"\"\n",
    "linspace = cirq.Linspace(start=0, stop=1.0, length=11, key='x')\n",
    "for p in linspace:\n",
    "    print(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "r-CjbPwkRI_I"
   },
   "source": [
    "### Exercise: Rotate a qubit\n",
    "\n",
    "Let's do the equivalent of a Rabi-flop experiment.  That is, let's apply a `XPowGate` rotating about the `X` axis for a linearly spaced set of values followed by a computational basis measurement.  The end result should be a plot of the sampled fraction that were $|1\\rangle$ as a function of gates of $X^t$ for $t$ between 0 and $1$ for 100 values of $t$ and each result sampled 100 times."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "id": "8yW2e3sq9JM8"
   },
   "outputs": [],
   "source": [
    "# Your code here!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "930ee2edd71b"
   },
   "source": [
    "## Noise"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FEM73JPALREa"
   },
   "source": [
    "In addition to circuits with unitary gates, Cirq also has support for modeling noisy quantum evolutions. This is useful when modeling what will happen when running on actual hardware.\n",
    "\n",
    "Cirq currently supports noise that fits within the context of *operator sum representations* of noise (a.k.a quantum operations, quantum dyanamical maps, superoperators, etc).  This formalism models the evolution of a density matrix via \n",
    "\n",
    "$$ \n",
    "\\rho \\rightarrow \\sum_k A_k \\rho A_k^\\dagger \n",
    "$$\n",
    "\n",
    "where the $A_k$ are *Kraus operators*.  These operators are not necessarily unitary and satisfy the property\n",
    "\n",
    "$$ \n",
    "\\sum_k A_k^\\dagger A_k = I . \n",
    "$$\n",
    "\n",
    "An example of a noise operator is the depolarizing channel on one qubit.  This takes\n",
    "\n",
    "$$\n",
    "\\rho \\rightarrow (1-p) \\rho + \\frac{p}{3} (X \\rho X + Y \\rho Y + Z \\rho Z) .\n",
    "$$\n",
    "\n",
    "In Cirq we can define such a channel and use it in a quantum circuit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "id": "YclVFbKZ0aD4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───D(0.2)───M───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Create a circuit with a depolarizing channel.\"\"\"\n",
    "circuit = cirq.Circuit(cirq.depolarize(0.2)(a), cirq.measure(a))\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CvteYd9s00t_"
   },
   "source": [
    "Previously we saw that gates could implement that `_unitary_` protocol, and by doing so they could be used to perform wave function simulation.  For noise the gates implement the `_channel_` protocol.  Classes that implement this protocol return the Krauss operators on their `_channel_` method.  Thus"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "id": "0ig_NSrS12PE"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Kraus operator 0 is:\n",
      "[[0.89442719 0.        ]\n",
      " [0.         0.89442719]]\n",
      "\n",
      "Kraus operator 1 is:\n",
      "[[0.        +0.j 0.25819889+0.j]\n",
      " [0.25819889+0.j 0.        +0.j]]\n",
      "\n",
      "Kraus operator 2 is:\n",
      "[[0.+0.j         0.-0.25819889j]\n",
      " [0.+0.25819889j 0.+0.j        ]]\n",
      "\n",
      "Kraus operator 3 is:\n",
      "[[ 0.25819889+0.j  0.        +0.j]\n",
      " [ 0.        +0.j -0.25819889+0.j]]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for i, kraus in enumerate(cirq.channel(cirq.depolarize(0.2))):\n",
    "    print(f\"Kraus operator {i} is:\", kraus, sep=\"\\n\", end=\"\\n\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4ee0055e4015"
   },
   "source": [
    "The Kraus operators are often more conveniently represented in a Pauli basis. We can do this in Cirq as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "id": "a2e5258ae33d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Kraus operator 0 is:\n",
      "0.894*I\n",
      "\n",
      "Kraus operator 1 is:\n",
      "0.258*X\n",
      "\n",
      "Kraus operator 2 is:\n",
      "0.258*Y\n",
      "\n",
      "Kraus operator 3 is:\n",
      "0.258*Z\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for i, krauss in enumerate(cirq.channel(cirq.depolarize(0.2))):\n",
    "    pauli_ex = cirq.expand_matrix_in_orthogonal_basis(krauss, cirq.PAULI_BASIS)\n",
    "    print(f\"Kraus operator {i} is:\", pauli_ex, sep=\"\\n\", end=\"\\n\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "spU2l26r0tQS"
   },
   "source": [
    "In addition to the wavefunction simulator, Cirq also has a density matrix simulator.  Instead of keeping track of the wavefunction, this simulator keeps track of the density matrix.  It has the same `run` and `simulate` type methods.  For example we can use this to simulate depolarizing channel and return the final density matrix of the system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "id": "skLIvXYq4yvX"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "a: ───D(0.2)───\n",
      "\n",
      "Final density matrix:\n",
      "[[0.8666666 +0.j 0.        +0.j]\n",
      " [0.        +0.j 0.13333333+0.j]]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Example of simulating a noisy circuit with the density matrix simulator.\"\"\"\n",
    "# Circuit to simulate.\n",
    "circuit = cirq.Circuit(cirq.depolarize(0.2)(a))\n",
    "print('Circuit:\\n{}\\n'.format(circuit))\n",
    "\n",
    "# Get the density matrix simulator.\n",
    "simulator = cirq.DensityMatrixSimulator()\n",
    "\n",
    "# Simulate the circuit and get the final density matrix.\n",
    "matrix = simulator.simulate(circuit).final_density_matrix\n",
    "print('Final density matrix:\\n{}'.format(matrix))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Eudp7NYo51LT"
   },
   "source": [
    "One thing to note is that the density matrix simulator simulates measurement statistically, and not as a channel where the outcome is not known. Consider the following example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "id": "_SjPRrIX5F4O"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulating a circuit with measurements using the DensityMatrixSimulator.\"\"\"\n",
    "# Get a circuit with measurements.\n",
    "circuit = cirq.Circuit(cirq.depolarize(0.5)(a), cirq.measure(a))\n",
    "\n",
    "# Simulate with the density matrix multiple times.\n",
    "dmat1 = simulator.simulate(circuit).final_density_matrix\n",
    "dmat2 = simulator.simulate(circuit).final_density_matrix\n",
    "\n",
    "print(np.allclose(dmat1, dmat2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "286ab4baf9fd"
   },
   "source": [
    "Because the final density matrix is statistical due to the measurements, the output of the above cell will change when executed multiple times."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3qUM-Kpi8Iy4"
   },
   "source": [
    "### Monte carlo simulations\n",
    "\n",
    "Density matrix simulations are more expensive than pure state wave function simulations.  However some channels allow an interpreation of randomly applying one of a fixed set of unitaries with differing probabilites.  For example the depolarizing channel above can be interpretted as: \n",
    "\n",
    "- With probability $1-p$ apply the identity to the state, and\n",
    "- with probability $p$ apply one of the three Pauli matrices $X$, $Y$, or $Z$ with equal probability.\n",
    "\n",
    "Channels that can be interpretted in this form can be simulating using a wavefunction simulator: when this channel is simulated the simulation will sample a unitary with the appropriate probability.  \n",
    "\n",
    "For channels of these type, the channel can, instead of implementing the `_channel_` protocol, implement the `_mixture_` protocol:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "id": "9Pt7o-Tq2SNz"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prob = 0.8\n",
      "unitary: \n",
      "[[1. 0.]\n",
      " [0. 1.]]\n",
      "\n",
      "prob = 0.06666666666666667\n",
      "unitary: \n",
      "[[0.+0.j 1.+0.j]\n",
      " [1.+0.j 0.+0.j]]\n",
      "\n",
      "prob = 0.06666666666666667\n",
      "unitary: \n",
      "[[0.+0.j 0.-1.j]\n",
      " [0.+1.j 0.+0.j]]\n",
      "\n",
      "prob = 0.06666666666666667\n",
      "unitary: \n",
      "[[ 1.+0.j  0.+0.j]\n",
      " [ 0.+0.j -1.+0.j]]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the cirq.mixture protocol on the cirq.depolarize channel.\"\"\"\n",
    "for p, u in cirq.mixture(cirq.depolarize(0.2)):\n",
    "    print(\"prob = {}\\nunitary: \\n{}\\n\".format(p, u))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "z4FIsadc4Nmg"
   },
   "source": [
    "In fact the depolarizing channel does not implement `_channel_`.  Instead it only implements `_mixture_` and the `cirq.channel` method notices this and derives the channel from the mixture."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "id": "HvhpBD334o1v"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "does cirq.depolarize(0.2) have _channel_? no\n",
      "does cirq.depolarize(0.2) have _mixture_? yes\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Check if cirq.depolarize has _channel_ and _mixture_ methods.\"\"\"\n",
    "# Get a depolarizing channel.\n",
    "d = cirq.depolarize(0.2)\n",
    "\n",
    "# Check if it has _channel_ implemented.\n",
    "print('does cirq.depolarize(0.2) have _channel_? {}'.format('yes' if getattr(d, '_channel_', None) else 'no'))\n",
    "\n",
    "# Check if it has _mixture_ implemented.\n",
    "print('does cirq.depolarize(0.2) have _mixture_? {}'.format('yes' if getattr(d, '_mixture_', None) else 'no'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OMCyapOd28h2"
   },
   "source": [
    "When channels implement mixture then, as we said, we can use the wavefunction simulator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "id": "vDEhGG0v-UJy"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a=0000000110\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the wavefunction simulator on a channel that implements the mixture protocol.\"\"\"\n",
    "circuit = cirq.Circuit(cirq.depolarize(0.5).on(a), cirq.measure(a))\n",
    "simulator = cirq.Simulator()\n",
    "result = simulator.run(circuit, repetitions=10)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a13d48d4836f"
   },
   "source": [
    "Because the unitary Kraus operators are applied stochastically, executing the above cell multiple times will produce different outputs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "weWPzaPx8zly"
   },
   "source": [
    "### Adding noise to circuits and simulations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "X-dT_CLu0fH9"
   },
   "source": [
    "To add noise to circuits or during simulations, we provide the notion of a `NoiseModel`.  A `NoiseModel` may add noise operation by operation, or it may add noise moment by moment, or it may add noise across a list of moments.\n",
    "\n",
    "For example we can define a noise model that add a single qubit depolarizing for every qubit in each moment.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "id": "PfRP7K598wNQ"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit with no noise:\n",
      "a: ───H───@───M───\n",
      "          │   │\n",
      "b: ───────X───M───\n",
      "\n",
      "Circuit with noise:\n",
      "a: ───H───D(0.2)[cirq.VirtualTag()]───@───D(0.2)[cirq.VirtualTag()]───M───D(0.2)[cirq.VirtualTag()]───\n",
      "                                      │                               │\n",
      "b: ───────D(0.2)[cirq.VirtualTag()]───X───D(0.2)[cirq.VirtualTag()]───M───D(0.2)[cirq.VirtualTag()]───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Adding noise to a circuit.\"\"\"\n",
    "# Get a noiseless circuit.\n",
    "noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\n",
    "circuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\n",
    "print('Circuit with no noise:\\n{}\\n'.format(circuit))\n",
    "\n",
    "# Add noise to the circuit.\n",
    "system_qubits = sorted(circuit.all_qubits())\n",
    "noisy_circuit = cirq.Circuit()\n",
    "for moment in circuit:\n",
    "    noisy_circuit.append(noise.noisy_moment(moment, system_qubits))\n",
    "print('Circuit with noise:\\n{}'.format(noisy_circuit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e4946d8f236f"
   },
   "source": [
    "We can also pass a noise model into the `cirq.DensityMatrixSimulator` and execute a noisy circuit in this manner."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "id": "uzxaFCGIz2aQ"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After step 0 state was\n",
      "[[0.4333333 +0.j 0.        +0.j 0.31777775+0.j 0.        +0.j]\n",
      " [0.        +0.j 0.06666666+0.j 0.        +0.j 0.04888888+0.j]\n",
      " [0.31777775+0.j 0.        +0.j 0.4333333 +0.j 0.        +0.j]\n",
      " [0.        +0.j 0.04888888+0.j 0.        +0.j 0.06666666+0.j]]\n",
      "\n",
      "After step 1 state was\n",
      "[[0.34859255+0.j 0.        +0.j 0.        +0.j 0.17089382+0.j]\n",
      " [0.        +0.j 0.15140739+0.j 0.02629136+0.j 0.        +0.j]\n",
      " [0.        +0.j 0.02629136+0.j 0.15140739+0.j 0.        +0.j]\n",
      " [0.17089382+0.j 0.        +0.j 0.        +0.j 0.34859255+0.j]]\n",
      "\n",
      "After step 2 state was\n",
      "[[0.75111103+0.j 0.        +0.j 0.        +0.j 0.        +0.j]\n",
      " [0.        +0.j 0.11555554+0.j 0.        +0.j 0.        +0.j]\n",
      " [0.        +0.j 0.        +0.j 0.11555553+0.j 0.        +0.j]\n",
      " [0.        +0.j 0.        +0.j 0.        +0.j 0.01777777+0.j]]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Perform noisy simulation by defining a density matrix simulator with a noise model.\"\"\"\n",
    "# Define a noise model.\n",
    "noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\n",
    "\n",
    "# Pass this noise model into the simulator.\n",
    "simulator = cirq.DensityMatrixSimulator(noise=noise)\n",
    "\n",
    "# Get a circuit to simulate.\n",
    "circuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\n",
    "\n",
    "# Simulate the circuit in steps.\n",
    "for i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n",
    "    print('After step {} state was\\n{}\\n'.format(i, step.density_matrix()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6308948de99a"
   },
   "source": [
    "## Devices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PvJCA3e0QsuI"
   },
   "source": [
    "NISQ algorithms work in a regime where every gate counts.  A key philosophy behind Cirq is that we believe the details of the hardware, the performance characteristics, as well as device constraints, will be key to getting the most out of NISQ algorithms.  Towards this end these hardware features are contained in the `Device` class.\n",
    "\n",
    "For example, here is Google's Bristleconde device which we printed out at the start of this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "id": "BmzxGpDB9jJ4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                             (0, 5)────(0, 6)\n",
      "                                             │         │\n",
      "                                             │         │\n",
      "                                    (1, 4)───(1, 5)────(1, 6)────(1, 7)\n",
      "                                    │        │         │         │\n",
      "                                    │        │         │         │\n",
      "                           (2, 3)───(2, 4)───(2, 5)────(2, 6)────(2, 7)───(2, 8)\n",
      "                           │        │        │         │         │        │\n",
      "                           │        │        │         │         │        │\n",
      "                  (3, 2)───(3, 3)───(3, 4)───(3, 5)────(3, 6)────(3, 7)───(3, 8)───(3, 9)\n",
      "                  │        │        │        │         │         │        │        │\n",
      "                  │        │        │        │         │         │        │        │\n",
      "         (4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)────(4, 6)────(4, 7)───(4, 8)───(4, 9)───(4, 10)\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "(5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)───(5, 5)────(5, 6)────(5, 7)───(5, 8)───(5, 9)───(5, 10)───(5, 11)\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "         │        │        │        │        │         │         │        │        │        │\n",
      "         (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)────(6, 6)────(6, 7)───(6, 8)───(6, 9)───(6, 10)\n",
      "                  │        │        │        │         │         │        │        │\n",
      "                  │        │        │        │         │         │        │        │\n",
      "                  (7, 2)───(7, 3)───(7, 4)───(7, 5)────(7, 6)────(7, 7)───(7, 8)───(7, 9)\n",
      "                           │        │        │         │         │        │\n",
      "                           │        │        │         │         │        │\n",
      "                           (8, 3)───(8, 4)───(8, 5)────(8, 6)────(8, 7)───(8, 8)\n",
      "                                    │        │         │         │\n",
      "                                    │        │         │         │\n",
      "                                    (9, 4)───(9, 5)────(9, 6)────(9, 7)\n",
      "                                             │         │\n",
      "                                             │         │\n",
      "                                             (10, 5)───(10, 6)\n"
     ]
    }
   ],
   "source": [
    "print(cirq.google.Bristlecone)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GGejgRf0AGni"
   },
   "source": [
    "In a future version, we intend for each `Device` to define a noise model.\n",
    "\n",
    "`Device`s also contain more information about the timing of the device.  For example here we can calculate the duration of an `X` on the `Bristlecone` device."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "id": "HAwdWkprAPXN"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20 ns\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Get the duration of an operation.\"\"\"\n",
    "brissy = cirq.google.Bristlecone\n",
    "op = cirq.X.on(cirq.GridQubit(5, 5))\n",
    "print(brissy.duration_of(op))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IxnyURhnAdph"
   },
   "source": [
    "Another property of devices is that they can be used to enforce constraints from the hardware, both checking that these constraints are satisfied, but also enforcing the constraints on the device.  For example, on the `Bristlecone` device, a two-qubit gate has the property that one cannot simultaneously perform a pair of two-qubit gates that act on adjacent qubits. So for example if we create such a `Circuit` and validate it using the device, we will see an error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "id": "r5F4FUtmA5kW"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(5, 5): ───@───\n",
      "           │\n",
      "(5, 6): ───@───\n",
      "\n",
      "(6, 6): ───@───\n",
      "           │\n",
      "(6, 7): ───@───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Validate operations on a device.\"\"\"\n",
    "# Get adjacent qubits on the Bristlecone device.\n",
    "q55 = cirq.GridQubit(5, 5)\n",
    "q56 = cirq.GridQubit(5, 6)\n",
    "q66 = cirq.GridQubit(6, 6)\n",
    "q67 = cirq.GridQubit(6, 7)\n",
    "\n",
    "# Define operations on adjacent qubits.\n",
    "ops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\n",
    "circuit = cirq.Circuit(ops)\n",
    "print(circuit)\n",
    "\n",
    "# cirq.google.Bristlecone.validate_circuit(circuit)\n",
    "# (this should throw an error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "XkNPbeFDBTL4"
   },
   "source": [
    "But more interestingly we could have passed the device into the `Circuit` and it will perform the creation of the circuit (using the insertion semantics as described above) such that the device cannot violate the constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "id": "5BOBUIEIBeQ5"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(5, 5): ───@───────\n",
      "           │\n",
      "(5, 6): ───@───────\n",
      "\n",
      "(6, 6): ───────@───\n",
      "               │\n",
      "(6, 7): ───────@───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Create a circuit for a particular device.\"\"\"\n",
    "# Same adjacent operations as above.\n",
    "ops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\n",
    "\n",
    "# Create a circuit on the Bristlecone device.\n",
    "circuit = cirq.Circuit(device=cirq.google.Bristlecone)\n",
    "\n",
    "\n",
    "# When we append operations now, they are put into different moments.\n",
    "circuit.append(ops)\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lyFcloaARXg4"
   },
   "source": [
    "### Exercise: Make a Device\n",
    "\n",
    "Construct a device that acts on a square sized lattice, and only allows Hadamard, CZ, and measurement gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "id": "zDE-19I_a3on"
   },
   "outputs": [],
   "source": [
    "# Your code here!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ed20ea519cc9"
   },
   "source": [
    "## Compiling / Optimizing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "J9ia4eatUQ_x"
   },
   "source": [
    "Cirq's philosophy for what are often called compilation steps is slightly non-traditional.  In particular we believe that NISQ devices perform so few gates that many compiliations will be one or a few passes. A useful class of optimization code for this is the `PointOptimizer`. For example, here is a `PointOptimizer` that recognizes that a `X` gate followed by a `Z` gate is equivalent to a `Y` gate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "id": "l7eFMVe1GEe2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before optimizing:\n",
      "a: ───X───Z───@───X───\n",
      "              │\n",
      "b: ───────────@───────\n",
      "\n",
      "After optimizing:\n",
      "a: ───Y───────@───X───\n",
      "              │\n",
      "b: ───────────@───────\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Example of defining a custom cirq.PointOptimizer.\"\"\"\n",
    "class XZOptimizer(cirq.PointOptimizer):\n",
    "    \"\"\"Replaces an X followed by a Z with a Y.\"\"\"\n",
    "    \n",
    "    def optimization_at(self, circuit, index, op):\n",
    "        # Is the gate an X gate?\n",
    "        if isinstance(op, cirq.GateOperation) and (op.gate == cirq.X):\n",
    "            next_op_index = circuit.next_moment_operating_on(op.qubits, index + 1)\n",
    "            qubit = op.qubits[0]\n",
    "            if next_op_index is not None:\n",
    "                next_op = circuit.operation_at(qubit, next_op_index)\n",
    "                if isinstance(next_op, cirq.GateOperation) and  (next_op.gate == cirq.Z):\n",
    "                    new_op = cirq.Y.on(qubit)\n",
    "                    return cirq.PointOptimizationSummary(\n",
    "                        clear_span = next_op_index - index + 1,\n",
    "                        clear_qubits=op.qubits, \n",
    "                        new_operations=[new_op])\n",
    "        \n",
    "opt = XZOptimizer()\n",
    "circuit = cirq.Circuit(cirq.X(a), cirq.Z(a), cirq.CZ(a, b), cirq.X(a))\n",
    "print(\"Before optimizing:\\n{}\\n\". format(circuit))\n",
    "opt.optimize_circuit(circuit)\n",
    "print(\"After optimizing:\\n{}\".format(circuit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "--aUfkiaUb3S"
   },
   "source": [
    "### Exercise: Simplify flipped CNOTs\n",
    "\n",
    "Write an PointOptimizer that performs (greedily) the simplification that\n",
    "\n",
    "```\n",
    "a: ───H───@───H───\n",
    "          │\n",
    "b: ───H───X───H───\n",
    "```\n",
    "is equal to\n",
    "\n",
    "\n",
    "```\n",
    "a: ───X───\n",
    "      │\n",
    "b: ───@───\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "id": "S0PThmctKFxl"
   },
   "outputs": [],
   "source": [
    "# Your code here!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "id": "75D9xMroKNDG"
   },
   "outputs": [],
   "source": [
    "\"\"\"Test your optimizer on this circuit.\"\"\"\n",
    "circuit = cirq.Circuit(\n",
    "    cirq.H.on_each(a, b, c), \n",
    "    cirq.CNOT(a, b), \n",
    "    cirq.H.on_each(a, b), \n",
    "    cirq.CZ(a, b)\n",
    ")\n",
    "# Instantiate your optimizer\n",
    "# my_opt = \n",
    "\n",
    "# And check that it worked.\n",
    "# print(my_opt.optimizer_circuit(circuit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "82c692df49dd"
   },
   "source": [
    "## Google's Xmon Gates"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "gM1ZW7TstvK9"
   },
   "source": [
    "We built Cirq at Google because we thought that it was important that hardware details flow up through the level of abstractions in a framework for NISQ algorithms.  And we also built it because Google has a class of superconducting qubit devices where we want to explore NISQ algorithms.  \n",
    "\n",
    "What sort of gates does the xmon architecture support?  At the hardware level the basic gate set is rotations about the Pauli $Z$ axis\n",
    "\n",
    "$$\n",
    "\\exp(-iZt) = \\left[ \n",
    "\\begin{matrix}\n",
    " e^{it} & 0 \\\\\n",
    " 0 & e^{-it}\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "$$\n",
    "\n",
    "Rotations about any axis in the Pauli $X$ and $Y$ plane:\n",
    "\n",
    "$$\n",
    "\\exp(-i(\\cos \\theta X + \\sin \\theta Y) t) = \n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "\\cos t & -i\\sin t e^{-i \\theta} \\\\\n",
    "-i\\sin t e^{i \\theta} & \\cos t\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "$$\n",
    "\n",
    "The two qubit gate is a phase about the $|11\\rangle$ state:\n",
    "\n",
    "$$\n",
    "\\exp(-it |11\\rangle \\langle 11|) =\n",
    "\\left[ \n",
    "\\begin{matrix}\n",
    "1 & 0 & 0 & 0 \\\\\n",
    "0 & 1 & 0 & 0 \\\\\n",
    "0 & 0 & 1 & 0 \\\\\n",
    "0 & 0 & 0 & \\exp(-it)\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "$$\n",
    "\n",
    "And finally measurements in the computational basis.\n",
    "\n",
    "Many of the common gates in Cirq are directly accessible on this hardware.  To check whether the gate you are using is in the xmon gate set, one can use the `is_supported_operation` as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "id": "feb179abdf97"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"Check if an operation is supported by the XMON gate set.\"\"\"\n",
    "# Get the XMON gate set.\n",
    "xmon = cirq.google.gate_sets.XMON\n",
    "\n",
    "# Check if X is supported.\n",
    "xmon.is_supported_operation(cirq.X.on(cirq.NamedQubit(\"a\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d6031d18fecd"
   },
   "source": [
    "Thus, `cirq.X` is supported by the xmon gate set. As mentioned above, `cirq.CNOT` is not supported, so the following code block should return `False`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "id": "d168c7619994"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"Check if CNOT is supported.\"\"\"\n",
    "xmon.is_supported_operation(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4FEVSq1T2n2J"
   },
   "source": [
    "When a gate is not a native xmon gate, Cirq can often convert it to an xmon native gate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {
    "id": "AdqDGjqL2lI2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───Z^0.75────X^0.5────S^-1───Y^-0.5───@───S^-1───Y^0.5───Y^0.5─────Z^-0.75───\n",
      "                                         │\n",
      "b: ───X^-0.25───Y^-0.5───────────────────@───S^-1───Y^0.5───X^-0.25─────────────\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Convert a gate to xmon gates.\"\"\"\n",
    "# Get a converter.\n",
    "converter = cirq.google.ConvertToXmonGates()\n",
    "\n",
    "# Do the conversion.\n",
    "converted = converter.convert(cirq.CNOT.on(cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")))\n",
    "print(cirq.Circuit(converted))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iR8zA_uY4HRZ"
   },
   "source": [
    "This isn't very optimized because what it has done is first rely on the decompose of `CNOT` and then decomposed each of these into native xmon gates.  There are many tricks that one can use to simplify xmon gates.  To apply many of these one can use the `cirq.google.optimize_from_xmon` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "id": "ePc0hrEU2_yy"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: ───PhXZ(a=0.375,x=1,z=0)────@───PhXZ(a=-0.625,x=1,z=0)────\n",
      "                               │\n",
      "b: ───PhXZ(a=-0.5,x=0.5,z=0)───@───PhXZ(a=-0.5,x=0.5,z=-1)───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Optimize a circuit for the xmon gate set.\"\"\"\n",
    "circuit = cirq.Circuit(\n",
    "    cirq.CNOT.on(cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\"))\n",
    ")\n",
    "print(cirq.google.optimized_for_xmon(circuit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lImnJ5Co4Y1n"
   },
   "source": [
    "Because xmon gates can be executed on Google hardware, they will need to be transmitted as machine code to the quantum computer.  This means that they have a serialized form.  We use protobuffers as the serialization.  To see what this form looks like we can do the following."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {
    "id": "od6ofvow4EoD"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "gate {\n",
       "  id: \"xy\"\n",
       "}\n",
       "args {\n",
       "  key: \"axis_half_turns\"\n",
       "  value {\n",
       "    arg_value {\n",
       "      float_value: 0.0\n",
       "    }\n",
       "  }\n",
       "}\n",
       "args {\n",
       "  key: \"half_turns\"\n",
       "  value {\n",
       "    arg_value {\n",
       "      float_value: 1.0\n",
       "    }\n",
       "  }\n",
       "}\n",
       "qubits {\n",
       "  id: \"5_5\"\n",
       "}"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"Serialize an operation.\"\"\"\n",
    "xmon.serialize_op(cirq.X.on(cirq.GridQubit(5, 5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b13526b78348"
   },
   "source": [
    "## Other interesting things in Cirq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tMC-nLE474nH"
   },
   "source": [
    "**Experiments**. The `cirq.experiments` package can perform and plot the results of some basic experiments for understanding how well a system is performing.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "id": "Ih8YgwX19h2-"
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAewAAAHgCAYAAABn6F4bAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8vihELAAAACXBIWXMAAAsTAAALEwEAmpwYAABNjklEQVR4nO3deXwTZf4H8E96AaVcrS0USguCCFRRDlGEXdQFL1jvlcpQcD0RXfFAF+kKCoZDUVdwf4gXIswqu9h1FQ9cEdcDEAXlqCxQpAEEetBSKG3pld8fD5P0mMnRJpnMzOf9evmazCSkT2PSb57j+31sTqfTCSIiIgprEXo3gIiIiLxjwCYiIjIABmwiIiIDYMAmIiIyAAZsIiIiA2DAJiIiMoCgBuw9e/Zg1KhRWLlyZZP7NmzYgFtuuQXjxo3D3/72t2A2g4iIyPCCFrDLy8sxZ84cDBs2TPX+Z555BosXL8Y777yDb7/9Frm5ucFqChERkeEFLWDHxMTgtddeQ1JSUpP7Dh48iA4dOiA5ORkREREYOXIkNm7cGKymEBERGV5U0J44KgpRUepPX1hYiPj4eNd5fHw8Dh482ORxW7ZsCVbziIiIwtLgwYNVrwctYAeKVsObY9euXejXr1/Ans+IrP4aWOr3l2Vg6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o1auXa+7d6XQ2qN1cV1fX4LkWLVqEESNG4LbbbsOnn36KL7/8EgBUfxciq+GQOFGIPfbYY1i4cCEqKipQUlKCLl26IDo6GuvWrUNtba1rqFrpOf700084++yzVZ9rzZo1ePbZZ/Hvf/8b//73v/Huu+/i008/1Qxoqamp2LlzJwDgq6++anJ/3759Xdc/+ugjbNy4scH9SUlJOHr0qOpzX3755aiqqnIF2bKyMiQnJ+PEiRP47rvvUF1djZ49e7p+/tatW5sMy5eUlCA1NRVOp9O1QYUn+fn5TXr8RGbFgE0UYt27d8dVV12FJUuW4NJLL4XD4cCECRNw8OBBXHbZZXjqqadcj508eTIWLVqEKVOmNHmekpIS7N69G7/97W9d11JSUtC9e3ds3bpV9WdPnDgRq1atwu233w4ATXYqysrKwtKlSzFhwgRkZ2ejX79+De4fMGAAdu/erZmS9sQTT2DevHk4ffo0xo8fj9tuuw1PPvkk7rrrLixduhT9+/dHZWUlJkyYgI8//rjJ1o7jxo3DnDlzcNddd2HMmDHYvHkzvvnmG83X8vvvv/crJY3IyLhbF5GF7N27FydOnMDgwYOxZs0aVxqWP+bNm4cLLrjANReul6KiItx7771YvXo107rIEhiwiSzk8OHDePTRR2Gz2RAREYF58+ahe/fufj1HWVkZ7r//fixatMiVi62HRx99FBMnTsQFF1ygWxuIQokBm4iIyAA4h01ERGQADNhEREQGwIBNRERkAAzYREREBsCATUREZAD/D/FCccQGyVF8AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 576x576 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "result = cirq.experiments.rabi_oscillations(\n",
    "    sampler=cirq.Simulator(),  # In the future, sampler could point at real hardware.\n",
    "    qubit=cirq.LineQubit(0)\n",
    ")\n",
    "result.plot();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "38c8tWcX90Zn"
   },
   "source": [
    "**Testing**. The `cirq.testing` package has useful debugging and testing methods like `cirq.testing.assert_implements_consistent_protocols` and `cirq.testing.assert_allclose_up_to_global_phase`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {
    "id": "j7FoZGKv90qe"
   },
   "outputs": [],
   "source": [
    "class InconsistentXGate(cirq.SingleQubitGate):\n",
    "\n",
    "    def _decompose_(self, qubits):\n",
    "        yield cirq.H(qubits[0])\n",
    "        yield cirq.Z(qubits[0])\n",
    "        yield cirq.H(qubits[0])\n",
    "\n",
    "    def _unitary_(self):\n",
    "        return np.array([[0, -1j], [1j, 0]])  # Oops! Y instead of X!\n",
    "\n",
    "# cirq.testing.assert_decompose_is_consistent_with_unitary(InconsistentXGate())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iYqy0qwU9sZy"
   },
   "source": [
    "**Export**. You can export a circuit as Qasm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {
    "id": "qH7xB-vZ-Jsn"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "// Generated from Cirq v0.9.1\n",
      "\n",
      "OPENQASM 2.0;\n",
      "include \"qelib1.inc\";\n",
      "\n",
      "\n",
      "// Qubits: [0, 1, 2]\n",
      "qreg q[3];\n",
      "\n",
      "\n",
      "h q[0];\n",
      "h q[2];\n",
      "cx q[0],q[1];\n",
      "h q[2];\n",
      "ccx q[0],q[1],q[2];\n",
      "h q[2];\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Export a circuit to Qasm.\"\"\"\n",
    "a, b, c = cirq.LineQubit.range(3)\n",
    "circuit = cirq.Circuit(cirq.H(a), cirq.H(c), cirq.CNOT(a, b), cirq.CCZ(a, b, c))\n",
    "print(circuit.to_qasm())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "35b3a411ffae"
   },
   "source": [
    "You can also export a circuit as QUIL:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "id": "951a57e8e0fd"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# Created using Cirq.\n",
      "\n",
      "H 0\n",
      "H 2\n",
      "CNOT 0 1\n",
      "H 2\n",
      "CCNOT 0 1 2\n",
      "H 2\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Export a circuit to QUIL.\"\"\"\n",
    "print(circuit.to_quil())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QlgFtRQs-TfQ"
   },
   "source": [
    "You can also turn a circuit into a link to the drag-and-drop web simulation Quirk (though somewhat inconveniently)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {
    "id": "Ydst5b0S9IGE"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "http://algassert.com/quirk#circuit=%7B%22cols%22%3A%5B%5B%22H%22%2C1%2C%22H%22%5D%2C%5B%22%E2%80%A2%22%2C%22X%22%5D%2C%5B%22%E2%80%A2%22%2C%22%E2%80%A2%22%2C%22Z%22%5D%5D%7D\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Export a circuit to a Quirk URL.\"\"\"\n",
    "from cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url\n",
    "print(circuit_to_quirk_url(circuit))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "KnA4uBkwEw5-"
   ],
   "name": "intro.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
